我需要做一个检查,看看他们输入的文件是否存在,我该如何做,我尝试使用try & catch,但没有效果
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文件夹中的卸载脚本来获取已安装应用程序的列表。我希望它是独立于目录的,这样我就可以让它获得当前目录
如果文件存在,我的代码就可以正常工作,但是如果文件不存在,代码就会崩溃,这就是我的问题
发布于 2009-11-16 08:40:55
try-catch无效,因为异常是由try块之外的代码引发的。正如其他答案指出的那样,您可以对代码进行一些改进,以便在真正异常的情况下调用您的异常处理。
发布于 2009-11-16 07:59:47
依赖异常进行正常处理并不是很好的做法。您可以使用File.Exists() function检查文件是否存在,如果不写入警报,则允许他们选择其他文件。所以它可能看起来像
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");
}https://stackoverflow.com/questions/1739347
复制相似问题