Apollo
Apollo

Reputation: 2070

Open browser via Command Prompt using C# code

I am trying to run the following code which opens command prompt and then passes the parameters which opens chrome and navigates to www.google.com

The browser needs to open from Command Prompt.

I know you have to use /c when you pass arguments.

I have tried the following:

 string arguments = "/c " + "\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe \"" + " www.google.com";
 string arguments = "/c " + "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe " + "www.google.com";

Any ideas why the browser is not opening and not passing the parameters?

Code

       public void ExecuteCmd()
       {

            int exitCode;
            string arguments ="/c " + @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe " + "www.google.com";
            // Prepare the process to run
            ProcessStartInfo start = new ProcessStartInfo();
            // Enter in the command line arguments, everything you would enter after the executable name itself
            start.Arguments = arguments;

            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            // Enter the executable to run, including the complete path
            start.FileName = @"C:\Windows\system32\cmd.exe";
            // Do you want to show a console window?
            start.WindowStyle = ProcessWindowStyle.Hidden;
            start.CreateNoWindow = true;

            // Run the external process & wait for it to finish
            using (Process proc = Process.Start(start))
            {
                string output = proc.StandardOutput.ReadToEnd(); 
                proc.WaitForExit();
                // Retrieve the app's exit code
                exitCode = proc.ExitCode;
            }
       }

Here is what it looks like if I do it manually. It opens Chrome and passes the parameter.

enter image description here

Upvotes: 0

Views: 2876

Answers (1)

Martin
Martin

Reputation: 2096

Use this:

string arguments = @"/c """"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"" http://www.google.de"""

That is, on the command prompt this would be equal to:

C:\>cmd /c ""C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" http://www.google.de"

Upvotes: 2

Related Questions