Process.Start()仅适用于在VisualStudio中以发布版本的形式启动时
问题描述:
我试图通过按按钮来执行外部.bat。Process.Start()仅适用于在VisualStudio中以发布版本的形式启动时
其意图是调用一些XCOPY指令。因此我使用Process.Start(startInfo)执行“sync.bat”。
该.bat的输出被重定向到我的应用程序并显示在对话框中。我的代码一直等到外部通话结束。
echo "Batch SYNC started."
pause
xcopy "e:\a\*" "e:\b\" /f /i /c /e /y
pause
echo "Batch SYNC finished."
OK: 当我建立我的节目为“释放”和内VisualStudio2013启动它,一切工作正常(我看到的结果,必须按ENTER键在黑色的窗口,文件复制)。
失败: 当我通过双击(在文件资源管理器或桌面)或VisualStudio的内部调试版本开始我的应用程序,我看到了ECHO和暂停输出,但批处理没有停下来,我看不到XCOPY的结果。看起来好像PAUSE和XCOPY立即被杀死。 我没有例外,并没有在Windows日志中的条目。
我试图使DEBUG和RELEASE配置相同(没有成功)。
有没有人有一个想法,我可以做些什么来让这个简单的功能在IDE之外工作?
这里是按下按钮时调用的函数的代码:
private void ProcessSync_bat()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.FileName = "sync.bat";
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.Arguments = "";
startInfo.ErrorDialog = true;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
dlgFKSyncMessageBox.AddLine("----------sync.bat started-----------");
dlgSyncMessageBox.AddLine("===============Result================");
while (!exeProcess.StandardOutput.EndOfStream)
{
dlgSyncMessageBox.AddLine(exeProcess.StandardOutput.ReadLine());
}
dlgSyncMessageBox.AddLine("===============ERRORS================");
while (!exeProcess.StandardError.EndOfStream)
{
dlgSyncMessageBox.AddLine(exeProcess.StandardError.ReadLine());
}
exeProcess.WaitForExit();
}
}
catch (Exception exp)
{
dlgSyncMessageBox.AddLine("========EXCEPTION========");
}
}
答
解决方案: 如果我还设置
startInfo.RedirectStandardInput = true;
然后它工作。我可能会将输入从对话框窗口重定向到进程。由于我不需要为预期的XCOPY提供任何输入,因此此解决方案对我而言不会在对话框窗口中捕获字符并转发到流程。 我看不到逻辑,为什么我必须重定向输入,但我很高兴我的软件现在可以满足我的需求。
你的bat文件是否复制了相应的输出文件夹?我怀疑你只是将它复制到'bin \ release',所以从'bin \ debug'运行时不会找到它。 – Filburt
你检查了答案在这里:https://stackoverflow.com/questions/21731783/xcopy-or-move-do-not-work-when-a-wcf-service-runs-a-batch-file-why你可能需要删除'RedirectStandardOutput'选项 – Bassie