windows 从 C# 运行 bat 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4004946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:28:08  来源:igfitidea点击:

Running bat script from C#

c#windowsprocessbatch-file

提问by Aly

I am trying to run a batch script from within a c sharp program the code I am using is shown below:

我正在尝试从 ac 锐利程序中运行批处理脚本,我使用的代码如下所示:

 Process proc = new Process();
 proc.StartInfo.FileName = "G:\Media\Downloads\print.bat";
 proc.Start();

The script is simple (for testing purposes) and contains one line:

该脚本很简单(用于测试目的)并包含一行:

echo hello > output.txt

When I run the script from windows explorer it works, but does not when run from the C# code.

当我从 Windows 资源管理器运行脚本时,它可以工作,但从 C# 代码运行时则不起作用。

any thoughts?

有什么想法吗?

Also how can I give the processes a callback method for when it has finished?

另外,如何为进程提供完成后的回调方法?

Thanks

谢谢

回答by Ani

It works fine for me. I'm guessing what's happening is that when you execute the batch file programmatically, you're expecting the output file to be created in the Downloadsfolder, when it's actually being created in the application'sfolder

这对我来说可以。我猜发生的事情是,当您以编程方式执行批处理文件时,您期望在文件Downloads夹中创建输出文件,而实际上是在应用程序的文件夹中创建

Either fully qualify the output file-path in the batch file or change the working directory of the launched process, like this:

要么完全限定批处理文件中的输出文件路径,要么更改启动进程的工作目录,如下所示:

proc.StartInfo.WorkingDirectory = @"G:\Media\Downloads\";

As for your question about receiving notification when the process has finished, you can use the WaitForExitmethod or the Exitedevent on the Processobject.

至于你关于进程完成后接收通知的问题,你可以使用对象上的WaitForExit方法或Exited事件Process