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

3 comments Write a comment