简体   繁体   中英

C# Change folder and start process in CMD, wait for it to finish

I need to open an external process from my Windows Forms app. What's more, I need to do it several times during the app's run time. Basically, I'm executing a .exe file with arguments several times from the command prompt, however I need to change the folder to where the .exe is in order for it to work properly. So far, I'm opening the cmd like so:

 ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
        processStartInfo.RedirectStandardInput = true;
        processStartInfo.RedirectStandardOutput = true;
        processStartInfo.UseShellExecute = false;

        Process process = Process.Start(processStartInfo);

Then using the process.WriteLine to feed commands to the CMD.

process.StandardInput.WriteLine("Awin.exe -X " + filePath + "/" + fileNumber + " ID=\"" + id + "\"");

And I need t do this for several fileNumber files. Also, I need to wait for the process started from the input to end before going on to the next one. Is there a better way to do this, because I'm not getting good results from using process.WaitForExit

ProcessStartInfo class has a WorkingDirectory property.

ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
processStartInfo.WorkingDirectory = your_directory
(...)

//do your thing
Process process = Process.Start(processStartInfo);

Arguments can be passed via the Arguments property

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.

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