繁体   English   中英

如何从Process.Start引发FileNotFoundException

[英]How to Throw FileNotFoundException from Process.Start

我试图在可执行文件上调用Process.Start() 如果找不到该文件,则应将其复制到所需位置,然后重试。

根据文档 ,当FileNotFoundException The file specified in the startInfo parameter's FileName property could not be found. 的文件时Process.Start()可以引发FileNotFoundException The file specified in the startInfo parameter's FileName property could not be found.

基于此,以下似乎是一种合理的方法:

try
{
    Process.Start(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe");
}
catch (FileNotFoundException ex)
{
    File.Copy(@"Z:\Unused\Apps\IT Support App\IT Self Help.exe", @"C:\users\Angus.McAngerson\desktop");
    Process.Start(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe", "vdi");
}

但是, try块中的Start()只会抛出Win32Exception

System.dll中发生了类型为'System.ComponentModel.Win32Exception'的未处理的异常

消息:系统找不到指定的文件

错误代码:-2147467259

NativeErrorCode:2

我尝试将try代码更改为:

var procsi = new ProcessStartInfo(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe");
Process.Start(procsi);

但是结果相同。 我还尝试将BuildPlatform更改为x86x6Any CPU但没有任何区别。

为什么会这样呢? 如何抛出FileNotFoundException


更新

该文档指出:

FileNotFoundException异常:

找不到在startInfo参数的FileName属性中指定的文件。

在上述情况下,找不到文件,但是代码引发了另一个异常。 如果不是完全不正确的话,那至少是非常令人误解的。

我能想到的唯一解释是该程序尝试运行文件而不检查其是否存在。 这足够公平,但是在什么情况下FileNotFoundException甚至会发生?

这是文档中的错误吗?

除非它们与异常跟踪相关,否则在catch中执行语句确实不是一个好主意。

我不明白为什么不能使用File.Exists (因为您打算对FileNotFoundException不做任何事情)。 如果我们重写您的代码,那么它将是:

if (File.Exists(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe"))
{
    Process.Start(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe");
}
else
{
    File.Copy(@"Z:\Unused\Apps\IT Support App\IT Self Help.exe", @"C:\users\Angus.McAngerson\desktop\IT Self Help.exe");
    Process.Start(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe", "vdi");
}

如果查看Process.Start的文档,您会注意到这里有一个例外情况表,其中包括:

Win32Exception-打开关联文件时发生错误。

FileNotFoundException -PATH环境变量具有包含引号的字符串。

即使异常有点误导,看起来它对我的行为也正确

如果您在此处查看: https : //msdn.microsoft.com/zh-cn/library/system.componentmodel.win32exception(v=vs.110).aspx

它会向您显示,当尝试打开不存在的可执行文件时,您将获得Win32Exception。

因此,实际上,您的代码似乎运行正常。

但是,如果您确实想要FileNotFoundException,那么您将必须在运行进程之前自己做一些检查,然后自己抛出异常。

if(!File.Exists(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe"))
{
     throw new FileNotFoundException("This file was not found.");
}

编辑

似乎在文档中似乎存在错误,因为即使它声称能够,也无法抛出FileNotFoundException

因此,您可以处理Win32Exception或执行我上面建议的操作。

也许其他人可以对此有所启发?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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