5

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

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.

Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
Mohammad Adib
  • 788
  • 6
  • 19
  • 39

6 Answers6

4

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

Community
  • 1
  • 1
CharithJ
  • 46,289
  • 20
  • 116
  • 131
3

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

    }
}
Simon Egli
  • 31
  • 2
1

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.

Qosmo
  • 1,142
  • 5
  • 21
  • 31
0

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

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    You're taking the wrong approach. You should learn how to perform these tasks using the .Net framework; see the documentation on MSDN. – SLaks Sep 18 '11 at 04:11
  • The question is not about the approach. The quesion is how to execute commands. Those are given for example. – Evgeny Gorbovoy Aug 19 '21 at 11:45
0

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:

Community
  • 1
  • 1
Yahia
  • 69,653
  • 9
  • 115
  • 144
0

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.

manojlds
  • 290,304
  • 63
  • 469
  • 417