【问题标题】:How to easily run shell commands using c#?如何使用 c# 轻松运行 shell 命令?
【发布时间】:2015-10-31 07:48:50
【问题描述】:

如何使用 c# 运行命令提示符命令? 假设我想按顺序运行这些命令:

cd F:/File/File2/...FileX/
ipconfig
ping google.com

或类似的东西......有人可以制作这个方法吗:

void runCommands(String[] commands) 
{
    //method guts...
}

这样您的输入是一系列字符串命令(即 ["ipconfig","ping 192.168.192.168","ping google.com","nslookup facebook.com"),应在单个命令提示符下执行按照它们放入数组的特定顺序。谢谢。

【问题讨论】:

    标签: c# command-line command-line-arguments


    【解决方案1】:

    应该在特定的单个命令提示符下执行 它们放入数组的顺序

    您可以将命令序列写入bat文件并运行如下。

    // Start the child process.
     Process p = new Process();
     // Redirect the output stream of the child process.
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.RedirectStandardOutput = true;
     p.StartInfo.FileName = "YOURBATCHFILE.bat";
     p.Start();
     // Do not wait for the child process to exit before
     // reading to the end of its redirected stream.
     // p.WaitForExit();
     // Read the output stream first and then wait.
     string output = p.StandardOutput.ReadToEnd();
     p.WaitForExit();
    

    Reference

    【讨论】:

      【解决方案2】:

      为此,我编写了一个动态类 Shell。你可以这样使用它:

      var shell = new Shell();
      
      shell.Notepad("readme.txt"); // for "notepad.exe readme.txt"
      shell.Git("push", "http://myserver.com"); // for "git push http://myserver.com"
      shell.Ps("ls"); // for executing "ls" in powershell;
      shell.Instance; // The powershell instance of this shell.
      

      这是类(它使用 System.Automation nuget 包来实现 powershell 功能):

      using System;
      using System.Collections.Generic;
      using System.Dynamic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.IO;
      using System.Diagnostics;
      using System.Management.Automation;
      
      namespace System.Diagnostics {
      
          public class Shell : System.Dynamic.DynamicObject {
      
              public Shell(): base() { }
              public Shell(bool window) { Window = window; }
      
              static string[] ScriptExtensions = new string[] { ".exe", ".cmd", ".bat", ".ps1", ".csx", ".vbs" };
      
              public string Path { get { return Environment.GetEnvironmentVariable("PATH"); } set { Environment.SetEnvironmentVariable("PATH", value); } }
      
              PowerShell pshell = null;
      
              public PowerShell Instance { get { return pshell ?? pshell = PowerShell.Create(); } }
      
              public bool Window { get; set; }
      
              public ICollection<PSObject> Ps(string cmd) {
                  Instance.AddScript(cmd);
                  return Instance.Invoke();
              }
      
              public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {
      
                  var exe = Path.Split(';').SelectMany(p => ScriptExtensions.Select(ext => binder.Name + ext)).FirstOrDefault(p => File.Exists(p));
      
                  if (exe == null) exe = binder.Name + ".exe";
      
                  var info = new ProcessStartInfo(exe);
                  var sb = new StringBuilder();
                  foreach (var arg in args) {
                      var t = arg.ToString();
                      if (sb.Length > 0) sb.Append(' ');
                      if (t.Contains(' ')) { sb.Append('"'); sb.Append(t); sb.Append('"'); } else sb.Append(t);
                  }
                  info.Arguments = sb.ToString();
                  info.CreateNoWindow = !Window;
                  info.UseShellExecute = false;
                  info.WindowStyle = Window ? ProcessWindowStyle.Normal : ProcessWindowStyle.Hidden;
                  try {
                      var p = Process.Start(info);
                      p.WaitForExit();
                      result = p.ExitCode;
                      return true;
                  } catch {
                      result = null;
                      return false;
                  }
              }
      
          }
      }
      

      【讨论】:

        【解决方案3】:

        我不会为你填空(鱼),而是给你鱼竿: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx

        查看 Process 类。

        【讨论】:

          【解决方案4】:

          您应该使用 .Net 等效项,可在 System.IOSystem.Net 中找到。

          【讨论】:

          • 您采取了错误的方法。您应该学习如何使用 .Net 框架执行这些任务;请参阅 MSDN 上的文档。
          • 问题不在于方法。问题是如何执行命令。举例来说。
          【解决方案5】:

          你想做什么?如果您正在考虑编写脚本并使用 .Net 框架,请查看 Powershell

          您可以使用您在 Powerhsell 脚本中提到的所有命令 - cd、ipconfig、nslookup、ping 等。

          【讨论】:

            【解决方案6】:

            Here你可以找到一个运行带有源代码的shell命令的解决方案......它甚至考虑了stderr。

            但正如@SLaks 指出的那样:使用 .NET 框架(即System.IOSystem.Net)有更好的方法来完成您所描述的事情!

            其他有趣的资源:

            【讨论】:

              猜你喜欢
              • 2010-10-25
              • 2012-09-17
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-04-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多