I am trying to get the output of a process. I've achieved this by using a .bat, which contains the following text:
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. 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. 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. 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}"
.
When you're on the command prompt you get "program execution" and ".bat/.cmd interactive scripting". Since you want to execute a batch file you need to tell CreateProcess that cmd.exe is what's actually running it.
The issue was just what I thought. The .bat file doesn't work properly when launched from an elevated app. 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. 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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.