running DOS commands using C#
Hello there......
i am developing an application and as a part of it i want to run DOS commands through my code. i am using C#. in the MSDN library i saw a mention of "System.Diagnostics.Process.Start" and using cmd.exe. but i am relly not sure how to use this, moreover there is no System.Diagnostics.Process? do i need any references?
please if someone could help....
thanks a lot.....
naaz
[587 byte] By [
naaz911] at [2008-2-10]
Process.start is a .net framework method and is available to all .net languages.
However as your using c# I would recommend asking the question in the C# Forums rather than the VB.Net ones
C# Forums
http://forums.microsoft.com/MSDN/default.aspx?forumgroupid=9&siteid=1
To use process start uses the system.diagnostics namespace which is in the default imports. I'm not sure what is in the default C# ones.
naaz,
It's strange you don't see System.Diagnostics.Process: it's in System.dll and I guess it's imported by default.
The simplest way to run a command is:
System.Diagnostics.Process.Start ("cmd", @"/c copy c:\myfolder\*.* c:\mybackup");
You can get creative using System.Diagnostics.ProcessStartInfo... for instance you can have your command run without showing a window and capturing the output of the command to process it as you prefer (for instance, displaying it in your console). A simple example of this follows:
// create the ProcessStartInfo using "cmd" as the program to be run, and "/c dir" as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
// To have more information, start cmd and type help cmd.
System.Diagnostics.ProcessStartInfo sinf =
new System.Diagnostics.ProcessStartInfo ("cmd", "/c dir");
// The following commands are needed to redirect the standard output. This means that it will be redirected to the Process.StandardOutput StreamReader.
sinf.RedirectStandardOutput = true;
sinf.UseShellExecute = false;
// Do not create that ugly black window, please...
sinf.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process p = new System.Diagnostics.Process ();
p.StartInfo = sinf;
p.Start (); // well, we should check the return value here...
// We can now capture the output into a string...
string res = p.StandardOutput.ReadToEnd ();
// And do whatever we want with that.
Console.WriteLine (res); HTH
--mc