Execute DOS From Windows Applications (C#)

Sometimes it is convenient to execute a dos script command from a windows application.  If you use C# doing so is not a big deal here is a sample code that should help execute or calling dos commands from a c#.net application:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
strCommand = @"/c   dir /w/a/p";
Process.Start("CMD.exe", strCommand).WaitForExit();
proc.Close();

I know you are probably saying that there are millions of web pages on the internet that give the same information. Well you are right, but the advantage of using ycsoftware.net is that all the codes are fully tested and supported.

What could go wrong with the above code?

The main thing that could go wrong is the DOS Command. How do you handle a space in a filename ? or how do you handle special characters?.  The Answer is: double quotes.

Let say you wanted to run this command.

wmaonly.bat  c:\\my document\yc software\net\m wma file.wma  c:\\mydocument\my new wma file.wma

How do you use the double quotes?

wrong:
@”/c wmaonly.bat  c:\\my document\yc software\net\m wma file.wma  c:\\mydocument\my new wma file.wma”

wrong:
@”/c ” + “wmaonly.bat  c:\\my document\yc software\net\m wma file.wma”  “c:\\mydocument\my new wma file.wma”

wrong:
@”/c ” + “wmaonly.bat ”  + “c:\\my document\yc software\net\m wma file.wma”  “c:\\mydocument\my new wma file.wma”

wrong:
@”/c ” + ‘”wmaonly.bat ”  + “c:\\my document\yc software\net\m wma file.wma”  “c:\\mydocument\my new wma file.wma”‘

right:
@"/c " + ""wmaonly.bat "  + "c:\\my document\yc software\net\m wma file.wma"  "c:\\mydocument\my new wma file.wma""

Note the double quotes

Let's share thisShare on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

3 comments Write a comment

  1. How ironic, your code will not work – you need to escape the quotes, i.e.
    @”/c ” + “\”wmaonly.bat ” + “c:\\my document\yc software\net\m wma file.wma” “c:\\mydocument\my new wma file.wma\””

  2. I took this verbatim from a running application that I wrote a couple of years ago. Last time i checked it worked flawlessly, but i will revisit it when i have a chance. Thanks for your comment.