C# 在某些命令上执行批处理文件超时
我正在使用以下代码执行批处理文件:C# 在某些命令上执行批处理文件超时,c#,batch-file,process,C#,Batch File,Process,我正在使用以下代码执行批处理文件: using (var process = new Process()) { process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/c \"\"" + batchFile + "\"\""; process.StartInfo.WorkingDirectory = Ap
using (var process = new Process())
{
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c \"\"" + batchFile + "\"\"";
process.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
var output = new StringBuilder();
var error = new StringBuilder();
using (var outputWaitHandle = new AutoResetEvent(false))
using (var errorWaitHandle = new AutoResetEvent(false))
{
process.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (process.WaitForExit(30000) &&
outputWaitHandle.WaitOne(30000) &&
errorWaitHandle.WaitOne(30000))
{
Log("Batch file exit code: " + process.ExitCode + ".\nOutput: " + output + ".\nError ouput: " + error);
}
else
{
Log("The batch file timed out.");
}
}
}
此代码执行批处理文件,并等待其完成。当我的批处理文件只输出到文本文件时,它工作正常。但是,如果我的批处理文件包含行start“C:\Windows\System32”notepad.exe
,则它将超时。为什么?
编辑
我刚刚意识到,即使批处理文件中只有notepad.exe
,它也会挂起,但如果我正在向文本文件写入,它可以正常工作。退出代码为无效操作
编辑
即使使用这个简单的代码,它也无法打开记事本。它也不会抛出任何异常或任何东西
string notepadPath = Path.Combine(Environment.SystemDirectory, "notepad.exe");
if (System.IO.File.Exists(notepadPath))
Process.Start(notepadPath);
检查
任务管理器
统计选项卡-我确信那里有很多记事本。您正在使用
StartInfo.CreateNoWindow=true创建流程
代码>。这将防止notepad
窗口打开,因为没有窗口-没有记事本。同样的行为也适用于UseShellExecute=false代码>
删除这些行并再次尝试(并确保是否存在记事本路径
文件,如果手动运行该批处理,则会打开记事本)
:
因此,您只需创建流程,而批处理正在等待它关闭,这是永远不会发生的。超时是什么意思。。它是否启动notepad.exe。。?还是当它挂起来的时候。。您是否尝试过在文件路径中使用文字符号?可能它正在将“\”
视为转义符号。。您是否已经使用调试器逐级检查了代码,以查看是否发生了特定的情况。。如果您更改了此行process.StartInfo.Arguments=“/c\”\”“+batchFile+”\”,该怎么办
到以下process.StartInfo.Arguments=“/c\“\\\”+批处理文件+“\”
为什么在最后需要额外的“\”
以及出于调试目的,我建议设置CreateNoWindow
,RedirectStandardInput
和RedirectStandardOutput
到false
。这可能会让您对问题有一些了解(即,您可能在控制台窗口中有一些输出)。在我的任务管理器中有很多记事本(还有cmd)!但是删除这些行仍然不会显示记事本…您希望通过process.BeginOutputReadLine()从notepad
中得到什么代码>?我想你永远不会从Notepad得到什么好的,我只是在一个单独的控制台应用程序项目中尝试了这段代码,它工作得很好。我认为问题是,我现在运行的应用程序本身没有窗口,它是一个在后台运行的进程…所以它可能无法打开任何其他窗口本身?嗯,是的,我认为问题在这里,因为你不能以这种方式打开窗口。
// This code assumes the process you are starting will terminate itself.
// Given that is is started without a window so you cannot terminate it
// on the desktop, it must terminate itself or you can do it programmatically
// from this application using the Kill method.