我想在。net 6控制台应用程序中启动一个带有一些参数的进程,以运行一个同样是在。net 6中创建的dll。
当我尝试cmd:> dotnet myPath/myApp.dll testParam
一切正常
但是当我尝试使用:
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();
我得到以下异常
System.ComponentModel。Win32Exception: '试图启动进程'dotnet myPath/myApp.dll testParam',工作目录'myPath'.
当我尝试将异常中的字符串复制并粘贴到cmd中时,它工作得很好。
我尝试设置工作目录,如下所示
请参阅文档https://learn.microsoft.com/en-us/dotnet/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();
我在使用。net时遇到了同样的问题
我的解决方案是使用这个扩展方法。它是在浏览器中打开url,但它也可能适用于任何exe。试一试吧。
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;
}
}
}