简体   繁体   中英

How to redirect command prompt output to a file using asp.net C#?

I have tried to redirect the command prompt output to a file using Asp.Net C#.

System.Diagnostics.Process si = new System.Diagnostics.Process();
si.StartInfo.WorkingDirectory = "c:\\";
si.StartInfo.UseShellExecute = false;
si.StartInfo.FileName = "cmd.exe";
si.StartInfo.Arguments = @"/c dir" +">" + @"Myval.txt";
si.StartInfo.CreateNoWindow = true;
si.StartInfo.RedirectStandardInput = true;
si.StartInfo.RedirectStandardOutput = true;
si.StartInfo.RedirectStandardError = true;
si.Start();
string output = si.StandardOutput.ReadToEnd();
Response.Write(output);
si.Close();

The file is getting created successfully but no content present in it. Even the variable Output returns nothing. Help me to resolve this issue.

EDIT after being corrected:

I just tested on my machine and the code works perfectly. I apologize for not reading and testing carefully myself. Myval.txt is created and the DIR output is written into it.

The output variable is empty because you are rerouting any output by the DIR command into the txt file, so that's by design.

Please see if there are any locks on the txt file preventing it from being overwritten. Further than that, I can only guess that there is a security issue preventing the DIR command from running.

IIS7 - I tested this various ways including using a Batch file but the application isn't available on desktop. I can see the worker process and the exe running under my user name but with session id value of zero.

The following has worked for me through command prompt:

// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "YOURBATCHFILE.bat";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM