使用 C# 以编程方式运行命令行代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13738168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run command line code programmatically using C#
提问by CNB
I'm using this code run in windows command prompt.. But I need this done programmatically using C# code
我正在使用在 Windows 命令提示符下运行的此代码。但我需要使用 C# 代码以编程方式完成此操作
C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -pdf "connection Strings" "C:\Users\XXX\Desktop\connection string\DNN"
C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -pdf "连接字符串" "C:\Users\XXX\Desktop\连接字符串\DNN"
采纳答案by Darin Dimitrov
You may use the Process.Startmethod:
您可以使用以下Process.Start方法:
Process.Start(
@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe",
@"-pdf ""connection Strings"" ""C:\Users\XXX\Desktop\connection string\DNN"""
);
or if you want more control over the shell and be able to capture for example the standard output and error you could use the overloadtaking a ProcessStartInfo:
或者,如果你想在外壳更多的控制,能够捕捉到例如标准输出和错误,你可以使用the overload采取ProcessStartInfo:
var psi = new ProcessStartInfo(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe")
{
Arguments = @"-pdf ""connection Strings"" ""C:\Users\XXX\Desktop\connection string\DNN""",
UseShellExecute = false,
CreateNoWindow = true
};
Process.Start(psi);
回答by wizzardz
You should be able to do that using a process
您应该能够使用流程来做到这一点
var proc = new Process();
proc.StartInfo.FileName = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe ";
proc.StartInfo.Arguments = string.Format(@"{0} ""{1}""" ""{2}""","-pdf","connection Strings" ,"C:\Users\XXX\Desktop\connection string\DNN");
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
string outPut = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
var exitCode = proc.ExitCode;
proc.Close();
回答by Microsoft DN
try this
尝试这个
ExecuteCommand("Your command here");
call it using process
使用过程调用它
public void ExecuteCommand(string Command)
{
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
Process = Process.Start(ProcessInfo);
}

