简体   繁体   中英

Using Process.Start to run a .NET 6 dll

I want to start a process with some arguments out of a .NET 6 console application to run a dll that was also created in .NET 6.

When I try to cmd: > do.net myPath/myApp.dll testParam everything works fine

but when I try to use:

Process process = new Process();
        process.StartInfo.FileName = "dotnet myPath/myApp.dll";
        process.StartInfo.WorkingDirectory = "myPath";
        process.StartInfo.Arguments = "testParam";
        process.StartInfo.UseShellExecute = false;
        process.Start();

I'm getting the following exception

System.ComponentModel.Win32Exception: 'An error occurred trying to start process 'do.net myPath/myApp.dll testParam' with working directory 'myPath'.

As I try to copy and paste the string out of the exception into cmd, it works just fine.

I tried to set the working directory, as explained here

Please see the documentation https://learn.microsoft.com/en-us/do.net/api/system.diagnostics.process?view.net-6.0

var dllPath = Path.Combine("myPath", "myApp.dll");

using Process process = new Process();
process.StartInfo.FileName = "dotnet"; // Append ".exe" if on windows
process.StartInfo.Arguments = $"{dllPath} testParam";
process.StartInfo.UseShellExecute = false;
process.Start();

I've run into the same issue when using .NET

The solution for me was to use this extension method. It is to open URLs in the browser but it might work for any exe as well. Just give it a try.

public static void OpenUrl(string url)
{
    try
    {
        Process.Start(url);
    }
    catch
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            url = url.Replace("&", "^&");
            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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM