[英]Process.Start("IExplore.exe"); --> System.IO.FileNotFoundException
一直在尝试运行这个简单的代码,它让我发疯,因为它不起作用。
我还期望 Visual Studio 在出现错误的行中中断程序,但它在 function 调用中中断,而不是在 function 内部中断,如下图所示。
OpenFolder();
private void OpenFolder()
{
Process.Start("explorer.exe", @"c:\temp");
}
我得到:
System.IO.FileNotFoundException:'无法加载文件或程序集'System.Diagnostics.Process,版本 = 4.1.0.0,文化 = 中性,PublicKeyToken = b03f5f7f11d50a3a'。 该系统找不到指定的文件。'
问题原因:因为UseShellExecute在.NET上默认为false 6.当UseShellExecute = false时,代码会使用传入的参数作为文件名,抛出“系统找不到指定的文件”异常。
原因:
UseShellExecute 在 .NET 6 上默认为 false:
public bool UseShellExecute { get; set; }
在 .NET 框架上默认为 true:
[DefaultValue(true)]
[MonitoringDescription("ProcessUseShellExecute")]
[NotifyParentProperty(true)]
public bool UseShellExecute
{
get
{
return this.useShellExecute;
}
set
{
this.useShellExecute = value;
}
}
private bool useShellExecute = true;
解决方案:
.Net6中的代码测试:
private void button1_Click(object sender, EventArgs e)
{
// Define an instance of processstartinfo
ProcessStartInfo startinfo = new ProcessStartInfo("explore.exe");
startinfo.FileName = @"C:\test\test.txt";
startinfo.UseShellExecute = true;
// start the process
try
{
Process.Start(startinfo);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
试验结果:
UseShellExecute 默认为 false:
private void button1_Click(object sender, EventArgs e)
{
// Define an instance of processstartinfo
ProcessStartInfo startinfo = new ProcessStartInfo("explore.exe");
startinfo.FileName = @"C:\test\test.txt";
// start the process
try
{
Process.Start(startinfo);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
试验结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.