ShinoLexTazy
ShinoLexTazy

Reputation: 77

sending command into CMD in c#

I wanna simple send this string into cmd command line

string arg= "ffmpeg.exe - i " + txtInput.Text + " " + txtOutput.Text + "";

I tried this

Process.Start("cmd.exe", arg);

But nothing happen, so how can I execute this command in cmd without showing the cmd to the user?

Upvotes: 0

Views: 1387

Answers (3)

P.Brian.Mackey
P.Brian.Mackey

Reputation: 44295

cmd.exe simply launches a new command prompt instance. This is similar to using powershell.exe. When you are already in cmd and run cmd there's not a difference. Try swapping between powershell.exe and cmd.exe and it's noticeable.

Run cmd /? to display a list of arguments you can run against cmd. One of which is cmd /C:

/C Carries out the command specified by string and then terminates

You asked "how can I execute this command in cmd without showing the cmd to the user?". Well for that you also need ProcessStartInfo.CreateNoWindow = true. For example:

    void Main()
    {
        string arg = $"/C ffmpeg.exe - i ${txtInput.Text}  ${txtOutput.Text}";
        launch(arg);
    }


static void launch(string arg)
{
    Process proc = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = "cmd",
            Arguments = arg,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true//This is important
        }
    };

    proc.Start();
    proc.WaitForExit();//May need to wait for the process to exit too
}

Upvotes: 0

ShinoLexTazy
ShinoLexTazy

Reputation: 77

First thank you for the idea @fubo this code worked for me

 string arg2 = " -i \"E:\\Test Folder\\Sample.mp4\" \"E:\\Test Folder\\sample.avi";

            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "E:\\ffmpeg.exe";
            p.StartInfo.Arguments = arg2;
            p.Start();

now I can move on and keep digging ffmpeg deeper since I know how to execute it now :)

Upvotes: 0

fubo
fubo

Reputation: 46005

why not starting ffmpeg.exe directly instead of cmd.exe

Process proc = new Process();
proc.StartInfo.FileName = @"c:\foo\ffmpeg.exe";
proc.StartInfo.Arguments = "-i " + txtInput.Text + " -o " + txtOutput.Text;
proc.Start();
proc.WaitForExit();

Upvotes: 3

Related Questions