【问题标题】:How to redirect command prompt output to a file using asp.net C#?如何使用 asp.net C# 将命令提示符输出重定向到文件?
【发布时间】:2014-05-27 18:20:15
【问题描述】:

我尝试使用 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 也没有返回任何内容。 帮我解决这个问题。

【问题讨论】:

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


    【解决方案1】:

    修正后编辑:

    我刚刚在我的机器上进行了测试,代码运行良好。我为自己没有仔细阅读和测试而道歉。 Myval.txt 被创建,DIR 输出被写入其中。

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

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

    【讨论】:

    • 顺便说一句,你想做什么?由于安全限制,您很有可能无法在托管环境中调用此类命令。
    • 我想在服务器端执行一个 exe,以便从用户输入中提取一些值并将输出收集到一个文件中。
    • 您至少需要一个 FullTrust 托管环境,但并非所有这些都允许您运行可执行文件。
    • 要尝试自托管。感谢您的帮助。
    • @Alexander,语法很好。它适用于控制台应用程序(注释掉 Response.Write)。输出变量为空,因为命令没有任何输出,输出保存到文件。要显示输出并保存到文件,他的命令应该是:@"/c dir >Myval.txt && type Myval.txt"。 /c 开关意味着 cmd 应该运行然后终止。请参阅ss64.com/nt/cmd.html 了解更多信息。但同意安全限制。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-22
        • 2012-12-25
        • 1970-01-01
        • 1970-01-01
        • 2018-06-07
        • 2017-07-06
        • 1970-01-01
        • 2012-09-16
        相关资源
        最近更新 更多