- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试对可执行文件调用 Process.Start()
。如果找不到该文件,应将其复制到所需位置,然后重试。
根据 the documentation , Process.Start()
可以在 找不到 startInfo 参数的 FileName 属性中指定的文件时抛出
FileNotFoundException
。
基于此,以下似乎是一种合理的方法:
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
block 中的 Start()
只会抛出 Win32Exception
:
An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll
Message: The system cannot find the file specified
ErrorCode: -2147467259
NativeErrorCode: 2
我尝试将 try
代码更改为:
var procsi = new ProcessStartInfo(@"C:\users\Angus.McAngerson\desktop\IT Self Help.exe");
Process.Start(procsi);
但是结果是一样的。我还尝试将 BuildPlatform 更改为 x86
、x6
和 Any CPU
但没有任何区别。
为什么会这样?如何抛出 FileNotFoundException
?
文档指出:
FileNotFoundException:
The file specified in the startInfo parameter's FileName property could not be found.
在上面的例子中,找不到文件,但代码抛出一个不同的异常。如果不是完全不真实的话,这至少是非常具有误导性的。
我能想到的唯一解释是程序试图运行文件而不检查它是否存在。这很公平,但是在什么情况下 FileNotFoundException
甚至会发生?
这是文档中的错误吗?
最佳答案
如果你看这里:https://msdn.microsoft.com/en-us/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 或执行我上面建议的操作。
也许其他人可以阐明这一点?
关于c# - 如何从 Process.Start 中抛出 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39487556/
我是一名优秀的程序员,十分优秀!