简体   繁体   English

从 C# 运行 .bat 文件不能像打开 .bat 文件那样工作

[英]Running a .bat file from C# doesn't work as opening the .bat file

I am trying to get the output of a process.我正在尝试获取进程的输出。 I've achieved this by using a .bat, which contains the following text:我通过使用 .bat 实现了这一点,其中包含以下文本:

program.exe > output.txt < input.txt

where program.exe is my executable, output.txt is the file I want to output the data to and input.txt is just an empty file since the program wants key inputs from time to time.其中 program.exe 是我的可执行文件,output.txt 是我想要将数据输出到的文件,input.txt 只是一个空文件,因为程序不时需要关键输入。 The .bat file works perfectly when I run it myself, but when I attempt to run it using C# code, it just doesn't finish properly. .bat 文件在我自己运行时运行良好,但是当我尝试使用 C# 代码运行它时,它无法正常完成。 I am trying to run it using the following code:我正在尝试使用以下代码运行它:

Process.Start(path);

I've tried a lot of different stuff but this is the code that I last tried but none of my attempts worked.我尝试了很多不同的东西,但这是我上次尝试的代码,但我的尝试都没有奏效。 Also, the .bat file doesn't run properly when you run it as an administrator and the C# program I am using is requiring administrator permissions.此外,当您以管理员身份运行 .bat 文件并且我使用的 C# 程序需要管理员权限时,它无法正常运行。 Could this be the issue and not the actual process running?这可能是问题而不是实际运行的进程吗?

You need to run the process cmd.exe /c [path] (aka the process is "cmd.exe", and your arguments are $"/c {path}" .您需要运行进程cmd.exe /c [path] (也就是进程是 "cmd.exe",你的参数是$"/c {path}"

When you're on the command prompt you get "program execution" and ".bat/.cmd interactive scripting".当您在命令提示符下时,您会看到“程序执行”和“.bat/.cmd 交互式脚本”。 Since you want to execute a batch file you need to tell CreateProcess that cmd.exe is what's actually running it.由于您要执行批处理文件,因此您需要告诉 CreateProcess cmd.exe 是实际运行它的内容。

The issue was just what I thought.这个问题正是我所想的。 The .bat file doesn't work properly when launched from an elevated app.从提升的应用程序启动时,.bat 文件无法正常工作。 To fix it I used this:为了修复它,我使用了这个:

Process.Start("explorer.exe", path);

Worked perfectly.完美地工作。 Fixed it really quickly but thought I'd leave this here if anybody finds himself stuck with the same thing.修复它真的很快,但我想如果有人发现自己陷入同样的​​事情,我会把它留在这里。

In ProcessStartInfo you should set UseShellExecute to false , then set WorkingDirectory in the path where you found that the bat is working correctly.ProcessStartInfo您应该将UseShellExecute设置为false ,然后在您发现 bat 正常工作的路径中设置WorkingDirectory Below is an example to make you understand better:下面是一个让你更好理解的例子:

using (Process MyProcess = new Process())
{
    var MyProcessInfo = new ProcessStartInfo()
    {
        UseShellExecute = false,
        WorkingDirectory = "path",
        FileName = "file.exe",
        Arguments = "args"
    };
    MyProcess.StartInfo = MyProcessInfo;
    MyProcess.Start();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM