如何使用C#轻松运行Shell命令?

5

我该如何使用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”]),这些命令应按照数组中放置的特定顺序在单个命令提示符上执行。谢谢。

6个回答

4
您可以将命令序列写入批处理文件并按以下方式运行,该命令序列应按照数组中放置的特定顺序在单个命令提示符上执行。
// 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


3
我写了一个动态类 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;
            }
        }

    }
}

1

0

你应该使用等价的 .Net 类库,可以在 System.IOSystem.Net 中找到。


2
你的方法不对。你应该学习如何使用 .Net 框架来执行这些任务;请参阅 MSDN 上的文档。 - SLaks
问题不在于方法。问题在于如何执行命令。这些命令是举例给出的。 - Evgeny Gorbovoy

0

0

你想做什么?如果你想要编写脚本并使用 .Net 框架,可以看看 Powershell

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接