如何使用asp.net C#将命令提示符输出重定向到文件?

时间:2013-07-25 06:29:37

标签: c# asp.net command-prompt io-redirection

我尝试使用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();

文件已成功创建,但其中没有内容。 即使变量Output也不返回任何内容。 帮我解决这个问题。

3 个答案:

答案 0 :(得分:1)

纠正后编辑:

我刚在我的机器上测试过,代码运行得很好。我为自己不仔细阅读和测试而道歉。创建Myval.txt并将DIR输出写入其中。

输出变量为空,因为您正在将DIR命令的任何输出重新路由到txt文件中,因此这是设计的。

请查看txt文件上是否有任何锁定,以防止被覆盖。除此之外,我只能猜测存在阻止DIR命令运行的安全问题。

答案 1 :(得分:0)

IIS7 - 我测试了各种方法,包括使用批处理文件,但桌面上没有应用程序。我可以看到工作进程和exe在我的用户名下运行,但会话ID值为零。

答案 2 :(得分:0)

以下内容通过命令提示符对我有用:

// 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();