[C#] - Invoke command prompt / Run process silently

Discussion in 'Mixed Languages' started by Josh Cell, Jan 16, 2012.

  1. Josh Cell

    Josh Cell MDL Developer

    Jan 8, 2011
    3,519
    7,096
    120
    #1 Josh Cell, Jan 16, 2012
    Last edited by a moderator: Apr 20, 2017
    This code will help you, in the command prompt calls as batch file non-enumerated commands:

    Use the System.Diagnostics namespace;

    Code:
            public static bool InvokePrompt(string Command)
            {
                try
                {
                    Process InvokePrompt = new Process();
                    InvokePrompt.StartInfo.FileName = Environment.GetEnvironmentVariable("COMSPEC");
                    InvokePrompt.StartInfo.Arguments = "/Q /K /C " + Command;
                    InvokePrompt.StartInfo.UseShellExecute = false;
                    InvokePrompt.StartInfo.RedirectStandardOutput = false;
                    InvokePrompt.StartInfo.CreateNoWindow = true;
                    InvokePrompt.Start();
                    InvokePrompt.WaitForExit();
                    InvokePrompt.Close();
                    return true;
                }
                catch { return false; }
            }
    For run any process silently:

    Code:
            public static bool InvokeProcess(string ProcessName, string Command)
            {
                try
                {
                    Process InvokeProcess = new Process();
                    InvokeProcess.StartInfo.FileName = ProcessName;
                    InvokeProcess.StartInfo.Arguments = Command;
                    InvokeProcess.StartInfo.UseShellExecute = false;
                    InvokeProcess.StartInfo.RedirectStandardOutput = false;
                    InvokeProcess.StartInfo.CreateNoWindow = true;
                    InvokeProcess.Start();
                    InvokeProcess.WaitForExit();
                    InvokeProcess.Close();
                    return true;
                }
                catch { return false; }
            }
    Examples:

    Code:
    InvokePrompt("MD C:\\MyFolder");
    InvokeProcess("C:\\Windows\\explorer.exe", "");
    
    The functions can return true for success, and false for error, the second way can run natively cmd process, as regedit.exe, or gpedit.msc...

    Good luck.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...