以编程方式运行命令行代码

时间:2012-12-06 06:32:53

标签: c# asp.net asp.net-mvc-3

我在windows命令promt中使用此代码运行.. 但我需要以编程方式使用c#代码完成,请帮助

  

C:\ Windows \ Microsoft.NET \ Framework \ v4.0.30319> aspnet_regiis.exe -pdf“连接   字符串“”C:\ Users \ XXX \ Desktop \ connection string \ DNN“

3 个答案:

答案 0 :(得分:18)

您应该能够使用流程

来实现这一目标
        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();

答案 1 :(得分:18)

试试这个

ExecuteCommand("Your command here");

使用流程

调用它
 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);
    }

答案 2 :(得分:12)

您可以使用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"""
);

或者如果您想要更多地控制shell并且能够捕获标准输出和错误,您可以使用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);