首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何捕获异常并继续编程?C#

如何捕获异常并继续编程?C#
EN

Stack Overflow用户
提问于 2009-11-16 07:53:14
回答 2查看 3.1K关注 0票数 1

我需要做一个检查,看看他们输入的文件是否存在,我该如何做,我尝试使用try & catch,但没有效果

代码语言:javascript
复制
if (startarg.Contains("-del") == true)
            {
                //Searches "Uninstallers" folder for uninstaller containing the name that they type after "-del" and runs it
                string uninstalldirectory = Path.Combine(Directory.GetCurrentDirectory(), "Uninstallers");
                DirectoryInfo UninstallDir = new DirectoryInfo(uninstalldirectory);
                string installname = startarg[2].ToString();
                //Removes file extesion "-del "
                installname.Remove(0, 5);
                string FullFilePath = Path.Combine(uninstalldirectory, installname);
                try
                {
                    //Makes the uninstaller invisible to the user and sets other settings
                    Process Uninstaller = new Process();
                    Uninstaller.StartInfo.FileName = FullFilePath;
                    Uninstaller.StartInfo.UseShellExecute = false;
                    Uninstaller.StartInfo.CreateNoWindow = true;
                    Uninstaller.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    Uninstaller.Start();
                }
                //Only is run if the package isn't installed
                catch (System.Exception)
                {
                    Console.WriteLine("The specified package is not installed, you most likely mispelled it or didnt put quotes around it, try again");
                }

            }

其中大部分代码都是获取当前目录并向其中添加"Uninstallers“。

编辑:调试结果为ArgumentOutOfRangeException

我尝试使用File.Exists if语句和else语句,但它仍然崩溃

编辑#2:

我正在尝试编写一个跨平台(使用mono,尚未移植,因为我不喜欢MonoDevelop)包管理器,这是它的删除包的功能。它通过获取应用程序的Uninstallers文件夹中的卸载脚本来获取已安装应用程序的列表。我希望它是独立于目录的,这样我就可以让它获得当前目录

如果文件存在,我的代码就可以正常工作,但是如果文件不存在,代码就会崩溃,这就是我的问题

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-11-16 08:40:55

try-catch无效,因为异常是由try块之外的代码引发的。正如其他答案指出的那样,您可以对代码进行一些改进,以便在真正异常的情况下调用您的异常处理。

票数 3
EN

Stack Overflow用户

发布于 2009-11-16 07:59:47

依赖异常进行正常处理并不是很好的做法。您可以使用File.Exists() function检查文件是否存在,如果不写入警报,则允许他们选择其他文件。所以它可能看起来像

代码语言:javascript
复制
if(File.Exists(FullFilePath))
{
   //uninstall
}
else
{
   Console.WriteLine("The specified package is not installed, you most likely mispelled it or didnt put quotes around it, try again");
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1739347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档