【问题标题】:Running batch file in C# code [duplicate]在 C# 代码中运行批处理文件 [重复]
【发布时间】:2013-04-07 07:42:39
【问题描述】:

请帮助我,我在特定位置有一个 .bat 文件,我想执行它并查看如果手动单击它会发生什么情况,问题是 .bat 文件作为弹出窗口运行只是片刻并且没有完成任何过程, 我的代码是这样的

int exitCode;
            ProcessStartInfo processInfo;
            Process process;
            string command = @"D:\programs\PreRef\Run.bat";
            processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
            //processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;
            // *** Redirect the output ***
            processInfo.RedirectStandardError = true;
            processInfo.RedirectStandardOutput = true;

            process = Process.Start(processInfo);
            process.WaitForExit();

            // *** Read the streams ***
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();

            exitCode = process.ExitCode;
            process.Close();

所以请帮我解决这个问题。注意这个.bat 文件运行另一个.exe 程序,.bat 文件中的文本类似于PreRef.exe "D:\programs\PreRef"

【问题讨论】:

  • @duDE 这不一定是重复的。
  • 只是为了调试工作,尝试更改/K 中的/c 参数并注释掉重定向进程输出的最后几行(只留下Process.Start 行)。现在您应该能够看到命令窗口并读取批处理文件的输出
  • 相同的@Steve 没有完成任何过程

标签: c#


【解决方案1】:

你可以试试这个:

Process objProcess = new Process();
objProcess.StartInfo.UseShellExecute = false;
objProcess.StartInfo.RedirectStandardOutput = true;
objProcess.StartInfo.CreateNoWindow = true;
objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;   
//file location
objProcess.StartInfo.FileName = string.Format(@"D:\programs\PreRef\Run.bat";");
//any argument 
objProcess.StartInfo.Arguments = string.Format("");
try
{
 objProcess.Start();
}
catch
{
 throw new Exception("Error");
}
StreamReader strmReader = objProcess.StandardOutput;
string strTempRow = string.Empty;
while ((strTempRow = strmReader.ReadLine()) != null)
{
    Console.WriteLine(strTempRow);
}
if (!objProcess.HasExited)
{
   objProcess.Kill();
}

【讨论】:

  • No Process 我没有看到任何结果@Arshad
  • 你的批处理文件工作了吗?
  • 是的,如果我手动执行它会很好用
  • 谢谢大家,我试过@SatpalSingh建议的链接,效果很好谢谢大家的帮助谢谢saptalSingh
  • @Arshad 为什么会捕捉到objProcess.Start(); 的异常并吞下可能包含有价值信息的异常。
猜你喜欢
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多