yonatan yonatan - 1 month ago 19
C# Question

c# run cmd with argument and close it in finish

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.WorkingDirectory = @"C:\";
startInfo.Arguments = "dir / s / b / o:n / A:D";
process.StartInfo = startInfo;
process.Start();


I try to run cmd with argument but it not working...

Answer

Remove the spaces between / and letters, so it looks like below:

System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.FileName = "cmd.exe";
            startInfo.WorkingDirectory = @"C:\";
            startInfo.Arguments = "/c dir /s /b /o:n /A:D";
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();

To wait for the process to end use process.WaitForExit();