Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Running a Command

Status
Not open for further replies.

stevenk140

Programmer
Nov 20, 2003
34
CA
I want to run a command like &quot;dir&quot; or &quot;del <filename&quot;. How do you do this in C#? In C\C++ you can do a System(cmd); What is the C# equivalent?

Steven
 
use this but it will not work on any internal commands

System.Diagnostics.Process.Start(@&quot;c:\yourfilename.exe&quot;);

takecare
 
You put everything in a .bat file and execute it or you can generate on the fly a temporary .bat file with the commands you want to execute and after that delete this .bat file .
Example:
C:\\tmp.bat contains;
echo Start > t1.lis
dir >> t1.lis
Now execute it with these statements:
Code:
System.Diagnostics.Process P = null;
try {
	P = new System.Diagnostics.Process();
	string WorkingDirectory = &quot;C:\\docs&quot;;
	//P.StartInfo.RedirectStandardOutput = true;
	P.StartInfo.CreateNoWindow = true;
	P.StartInfo.WorkingDirectory = WorkingDirectory;
	P.StartInfo.FileName =  &quot;C:\\tmp.bat&quot;;
	//P.StartInfo.Arguments = &quot;&quot;;				//P.EnableRaisingEvents = true;
	P.StartInfo.UseShellExecute = false;
	P.Start();
}
catch(Exception er)
{
	string sMsg = &quot;Error in starting process &quot; + er.GetType() + er.Message;
}
The C:\\tmp.bat is executed and the t1.lis file will be created in the workingdirectory e.g. C:\Docs\t1.lis
You also can capture the output of the tmp.bat by RedirectStandardOutput to true and use P.StandardOutput.ReadToEnd();
-obislavu-
 
Stevenk140 -

I'm assuming you used &quot;dir&quot; and &quot;del&quot; as examples? Because that functionality already exists in the .NET framework. Take a look in the System.IO namespace, at the DirectoryInfo class and the File class.

Chip H.



If you want to get the best response to a question, please check out FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top