C# 如果我需要启动的exe文件在计算机上不存在,则引发异常的常见方法是什么
在我的应用程序中,我启动了作为Wireshark一部分的capinfos.exe。 在构造器中,我检查Wireshark是否安装在机器上:C# 如果我需要启动的exe文件在计算机上不存在,则引发异常的常见方法是什么,c#,C#,在我的应用程序中,我启动了作为Wireshark一部分的capinfos.exe。 在构造器中,我检查Wireshark是否安装在机器上: private string _filePath = ""; public Capinfos(string capturePath) { if (Directory.Exists(@"C:\Program Files (x86)\Wireshark")) { _capInfos = @"C:\Program Files (x
private string _filePath = "";
public Capinfos(string capturePath)
{
if (Directory.Exists(@"C:\Program Files (x86)\Wireshark"))
{
_capInfos = @"C:\Program Files (x86)\Wireshark\capinfos.exe";
}
else if (Directory.Exists(@"C:\Program Files\Wireshark"))
{
_capInfos = @"C:\Program Files\Wireshark\capinfos.exe";
}
_filePath = capturePath;
}
如果计算机上不存在该文件,最好的方法是什么并引发异常:请安装Wireshark,如:
throw new FileNotFoundException("Could not find " + _capInfos, _capInfos);
不确定这是否是您想要的,但尝试使用块。您可以尝试在try块中启动.exe,如果失败,则抛出一个并在catch块中创建一个弹出框,提醒用户需要执行的操作
private string _filePath = "";
public Capinfos(string capturePath) throws FileNotFoundException
{
if (Directory.Exists(@"C:\Program Files (x86)\Wireshark"))
{
_capInfos = @"C:\Program Files (x86)\Wireshark\capinfos.exe";
}
else if (Directory.Exists(@"C:\Program Files\Wireshark"))
{
_capInfos = @"C:\Program Files\Wireshark\capinfos.exe";
} else
{
throw new FileNotFoundException(@"Wireshark installation not found");
}
_filePath = capturePath;
}
然后,您可以使用以下代码捕获异常:
try
{
Capinfos("path");
}
catch (FileNotFoundException ex)
{
Messagebox.Show("Please install wireshark.");
}
我没有安装C#,这是手写的。希望一切都好!
这里有一个很好的资源可以学习异常:将try-catch放在哪里?实际上,它只是一个普通的代码块。你可以把它放在main中,放在构造器中,任何你想放的地方。“在构造器中,我要检查Wireshark是否安装在机器上”-不,你不需要,你要检查一些exe是否存在于硬编码路径中。如果希望此代码可移植,应查看注册表以查找安装路径(在
HKEY\U LOCAL\U MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App path\wireshark.exe
)。