Click here to Skip to main content
15,891,567 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am want to run a command in cmd through c# code. For this purpose I used below two code

C#
System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "chkdsk";
            process.StartInfo = startInfo;
            process.Start();


and

C#
 ProcessStartInfo procStartInfo = new ProcessStartInfo("CMD.EXE", "defrag");
 procStartInfo.WindowStyle = ProcessWindowStyle.Maximized;
 procStartInfo.RedirectStandardOutput = true;
 procStartInfo.UseShellExecute = false;
 procStartInfo.CreateNoWindow = true;
 Process pro = new Process();
 pro.StartInfo = procStartInfo;
 pro.Start();

// string result = pro.StandardOutput.ReadToEnd();
// pro.WaitForExit();


The issue is , when I used first code then it open cmd but not run the command which I want and in case of second code it open cmd for just one second and it also does't run that command.
Can anybody help me in this matter.

Thank you.
Posted
Comments
Vedat Ozan Oner 14-Feb-14 8:33am    
the same question exists here: http://www.codeproject.com/Questions/720259/How-to-run-command-prompt-command-and-get-output-i
please search before asking.
AdityaBohra 15-Feb-14 1:00am    
Thanks Vedat, I searched before posting but this link was not visible to me.
Vedat Ozan Oner 15-Feb-14 4:22am    
are you sure? that is impossible.
AdityaBohra 15-Feb-14 6:03am    
Damn sure.
Vedat Ozan Oner 15-Feb-14 6:25am    
ok. would you like me to copy its content and paste here? and what you said may be a bug in the site. you can report it.

1 solution

You have to pass the /C switch to CMD.exe[^]. E.g.
REM Open a new explorer window
cmd.exe /C explorer.exe


But why pass it through cmd.exe in the first place?
 
Share this answer
 
Comments
AdityaBohra 15-Feb-14 0:59am    
Thanks Maarten, it's worked. But I don't understand what want to ask.
Maarten Kools 15-Feb-14 4:38am    
If you're going to run a program, for example chkdsk.exe, why do you want to call it through cmd.exe? I would think it's possible to directly call chkdsk. But if this works for you, you can also just leave it the way it is I suppose.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900