How to use more DOS commands in C#
I have about 7 commands in DOS and I want to run them in my C# program. Can I do:
System.Diagnostics.Process.Start("cmd.exe", "my more commands here");
? EDIT: I'm making small app what will run g++. Is this now correct?:
System.Diagnostics.Process.Start("cmd.exe", "/k cd C:\\Alps\\compiler\\ /k g++ C:\\Alps\\" + project_name + "\\Debug\\Main.cpp");
Command for compiling:
g++ -c C:开发者_如何学编程\Alps\here_is_projectname\Debug\Main.cpp -o main.o
cmd.exe /k <command>
cmd.exe /c <command>
Are both valid.
/k
will execute the command and leave you with an empty prompt (probably less desirable in your application if you just want to execute for feedback.)/c
will execute the command and close the window when it has completed.
If you're looking to execute a command from a specific directory, you can do:
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
p.StartInfo.Arguments = String.Format(@"/c g++ ""C:\Alps\{0}\Debug\Main.cpp""", project_name);
p.StartInfo.WorkingDirectory = @"C:\Alps\compiler";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.ErrorDialog = false;
p.Start();
Yes, you can pass in the command line using the "/C" switch:
System.Diagnostics.Process.Start("cmd.exe", "/C dir");
You can also do like the following....
Process.Start(new ProcessStartInfo()
{
Arguments = "args",
WorkingDirectory = "C:\SomePath",
UseShellExecute= true,
FileName = ".exe"
});
There are also options on the processstartinfo to redirect input and output if you need to
For example..
Process.Start(new ProcessStartInfo()
{
Arguments = "C:\\Alps\\" + project_name + "\\Debug\\Main.cpp",
WorkingDirectory = "C:\\Apls\\",
UseShellExecute= true,
FileName = "g++.exe"
});
You can launch cmd.exe redirect the stdin and feet that stream with your commands.
process.Start(...);
process.StandardInput.WriteLine("Dir xxxxx");
process.StandardInput.WriteLine("Dir yyyyy");
process.StandardInput.WriteLine("Dir zzzzzz");
process.StandardInput.WriteLine("other command(s)");
Of course you should remeber to set your process star info to say you want redirect input:
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe);
processStartInfo.CreateNoWindow = true;
processStartInfo.ErrorDialog = false;
processStartInfo.RedirectStandardInput = true;
精彩评论