首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >执行C# .bat文件时出现错误和输出重定向

执行C# .bat文件时出现错误和输出重定向
EN

Stack Overflow用户
提问于 2012-06-24 20:48:13
回答 1查看 2.6K关注 0票数 1

我有一个要执行的.bat文件。

.bat文件内部,其末尾是代码

代码语言:javascript
运行
复制
START _file_creator.bat %some_arg_name%
ENDLOCAL
EXIT

我不想在执行过程中显示窗口,而且我必须等到这个.bat文件所做的操作完成,然后终止执行(在操作结束时,我看到标准文本“按任意键继续”)。我还需要检查该文件的输出和错误,所以我尝试使用该代码:

代码语言:javascript
运行
复制
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo.FileName = @"C:\m_f\_config.bat";
        proc.StartInfo.RedirectStandardError = true;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.CreateNoWindow = true;

        proc.Start();
        proc.WaitForExit();
        output1 = proc.StandardError.ReadToEnd();
        proc.WaitForExit();
        output2 = proc.StandardOutput.ReadToEnd();
        proc.WaitForExit();

但我得到的只是错误

代码语言:javascript
运行
复制
Windows can not find file "_file_creator.bat".
Make sure you typed the name correctly and try again.

当然,如果我使用proc.StartInfo.UseShellExecute = true运行.bat文件,它可以正常工作,但在这种情况下,我不能设置RedirectStandardError = trueRedirectStandardOutput = true

如何修复它?

编辑

使用该代码,它现在可以工作了

代码语言:javascript
运行
复制
 proc.StartInfo.FileName = @"C:\m_f\_config.bat";
 proc.StartInfo.WorkingDirectory = @"C:\m_f\";
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-24 20:50:46

尝试正确设置工作目录或确保_file_creator.bat位于PATH中的某个位置。请参阅与UseShellExecute结合使用的有关工作目录的documentation

根据UseShellExecute属性的值,

WorkingDirectory属性的行为会有所不同。当UseShellExecutetrue时,WorkingDirectory属性指定可执行文件的位置。如果WorkingDirectory为空字符串,则假定当前目录包含可执行文件。

UseShellExecutefalse时,不使用WorkingDirectory属性查找可执行文件。相反,它仅由启动的进程使用,并且仅在新进程的上下文中有意义。当UseShellExecutefalse时,FileName属性必须是可执行文件的完全限定路径。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11177554

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档