在c#代码中运行批处理文件
本文关键字:运行 批处理文件 代码 | 更新日期: 2023-09-27 18:09:06
请帮助我,我有一个。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"
你可以试试:
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();
}