Process.Start(“microsoft-edge:”) gives me Win32Exception

北城余情 提交于 2019-12-06 02:50:00
M. Schena

You cannot simply open a url with the expected call Process.Start("url");

You have to create a ProcessStartInfo and pass your browser and url as arguments:

Process.Start(new ProcessStartInfo("cmd", $"/c start microsoft-edge:http://localhost") { CreateNoWindow = true });

(edit) The use of ProcessStartInfo is required because we need to set its CreateNoWindow = true to prevent cmd window from showing up.

But as this code not only can be run on a Windows machine, i'd consider using something more cross-platform specific like this (https://brockallen.com/2016/09/24/process-start-for-urls-on-net-core/):

public void OpenBrowser(string url)
{
    try
    {
        Process.Start(url);
    }
    catch
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            Process.Start("xdg-open", url);
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            Process.Start("open", url);
        }
        else
        {
            throw;
        }
    }
}

And call it with OpenBrowser("http://localhost");

Windows Run window (Win+R) know how to resolve "microsoft-edge:" to the Path Of Executable. When you call it through Run window, it first resolves to the path. Then the actual executable from that path is executed.

With Process.Start, there is no this resolution of path. It only look for some paths like application path or PATH variables. Obviously, it does not find the executable to run and hence the error.

If you have a path variable declared in your system using quotes, you must fully qualify that path when starting any process found in that location. Otherwise, the system will not find the path. For example, if c:\mypath is not in your path, and you add it using quotation marks: path = %path%;"c:\mypath", you must fully qualify any process in c:\mypath when starting it.

Source

Note that command line parameters are not allowed by this overload:

This overload does not allow command-line arguments for the process. If you need to specify one or more command-line arguments for the process, use the Process.Start(ProcessStartInfo) or Process.Start(String, String) overloads.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!