通过c#.net代码注册运行bat文件

时间:2012-08-22 06:35:40

标签: c# .net batch-file

我在c#中通过dotnet运行了bat文件,如下所示

Process p = new Process();
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.FileName = "d://s.bat";
                p.Start();
                string output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();

在通过dotnet ide运行时工作正常。

但我的问题是,当我通过IIS发布后运行上面的代码时它会返回错误

  

StandardOut-具有 - 不被重定向-或最过程不是招叔启动的爱好。

你可以给我一些指导方针来解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您必须使用RedirectStandardOutput = true。 来自MSDN

的链接

从链接引用:

  

ProcessStartInfo.RedirectStandardOutput属性   获取或设置一个值,该值指示应用程序的输出是否写入Process.StandardOutput流。

当我确定我们的服务器正在启动时,从我的问题到相同问题的片段。

if (IsProcessRunning(ServerProcessName)) { return; }
        var p = new Process
        {
            StartInfo = new ProcessStartInfo
                            {
                                FileName = path,
                                RedirectStandardOutput = true, 
                                UseShellExecute = false
                            }
        };
        p.Start();
        var a = "";
        while (!a.Contains("ServicesStarted"))
        {
            a = p.StandardOutput.ReadLine();
        }

答案 1 :(得分:1)

这样做,克服错误: -

StringBuilder content = new StringBuilder();
while ( ! p.HasExited ) {
    content.Append(p.StandardOutput.ReadToEnd());
}
string output = content.ToString();