简体   繁体   English

如果我需要启动的exe文件在计算机上不存在,抛出异常的常用方法是什么

[英]What is the common way to throw exception if my exe file that i need to start does not exist on the machine

in my application i am start capinfos.exe that is part of Wireshark. 在我的应用程序中,我启动Wireshark的capinfos.exe。 in the constructor i am check if Wireshark install on the machine: 在构造函数中,我正在检查是否在计算机上安装了Wireshark:

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;
}

what is the best way to do it and throw an exception if the file does not exist on the machine: please install Wireshark 最好的方法是什么,如果计算机上不存在该文件,则抛出异常:请安装Wireshark

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;
}

You can then catch the exception by using this code: 然后,您可以使用以下代码捕获异常:

   try
    {
        Capinfos("path");
    }
    catch (FileNotFoundException ex)
    {
        Messagebox.Show("Please install wireshark.");
    }

I don't have C# installed, this was written by hand. 我没有安装C#,这是手工编写的。 Hope it's fine! 希望一切都好! Here's an excellent resource to learn on exceptions: http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.80).aspx 这是学习异常的绝佳资源: http : //msdn.microsoft.com/zh-cn/library/0yd65esw(v=vs.80).aspx

就像是:

throw new FileNotFoundException("Could not find " + _capInfos, _capInfos);

Not sure if this is what you want, but try to use a try-catch block. 不知道这是否是您想要的,但是尝试使用try-catch块。 You could attempt to start the .exe in the try block and if it fails, throw a FileNotFoundException and create a popup box in the catch block that will alert the user of what they need to do. 您可以尝试在try块中启动.exe,如果失败,则抛出FileNotFoundException并在catch块中创建一个弹出框,该框将提醒用户他们需要做什么。

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

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