2013-07-25 42 views
2

我试图使用Asp.Net C#将命令提示符输出重定向到一个文件。如何使用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也不会返回任何结果。 帮我解决这个问题。修正后的

回答

1

编辑:

我刚刚测试了我的机器上的代码完美的作品。我很抱歉没有仔细阅读和测试自己。 Myval.txt被创建并且DIR输出被写入它。

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

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

+0

在一个侧面说明,什么是你想怎么办?由于安全限制,您很有可能无法在托管环境中调用此类命令。 – Alexander

+0

我想在服务器控制台执行一个exe文件,以便从用户输入中提取一些值并将输出收集到一个文件中。 – Dinesh

+0

您至少需要一个FullTrust托管环境,而不是所有这些都允许您运行可执行文件。 – Alexander

0

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

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(); 
相关问题