开发者

How to easily run shell commands using c#?

how do i use c# to run command prompt commands? Lets say i want to run these commands in a sequence:

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

or something like that...Can someone make this method:

void runCommands(String[] commands) 
{
    //method guts.开发者_如何学C..
}

such that your input is a series of string commands (i.e ["ipconfig","ping 192.168.192.168","ping google.com","nslookup facebook.com") that should be executed on a single command prompt in the specific sequence in which they are put in the array. Thanks.


that should be executed on a single command prompt in the specific sequence in which they are put in the array

You could write command sequence in a bat file and run as below.

// 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


I wrote a dynamic class Shell for this purpose. You can use it like so:

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.

Here's the class (It uses the System.Automation nuget package for powershell features):

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;
            }
        }

    }
}


I won't fill the blank (fish) for you but instead give you the rod: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx

Check out the Process class.


You should use the .Net equivalents, which can be found in System.IO and System.Net.


What are you trying to do? If you are looking at doing scripting and also use the .Net framework, have a look at Powershell

You can use all the commands that you mention as such in Powerhsell scripts - cd, ipconfig, nslookup, ping etc.


Here you can find a solution for running shell commands complete with source code... it even takes stderr into account.

BUT as @SLaks pointed out: there are better ways to do what you describe by using the .NET Framework (i.e. System.IO and System.Net)!

Other interesting resources:

  • http://msdn.microsoft.com/en-us/library/ccf1tfx0.aspx
  • http://msdn.microsoft.com/en-us/library/system.diagnostics.process.startinfo.aspx
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜