Jar*_*ner 1 c# exception try-catch
我需要检查一下他们输入的文件是否存在,我怎么能这样做,我尝试使用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");
}
}
Run Code Online (Sandbox Code Playgroud)
大部分代码都是获取当前目录并向其添加"卸载程序".
编辑:调试结果是ArgumentOutOfRangeException
我尝试使用File.Exists if语句,否则它仍然崩溃
编辑#2:
关于我要对这个程序做些什么:我正在尝试编写一个跨平台(有单声道,还没有移植它,因为我不喜欢MonoDevelop)包管理器,这就是函数它删除包.它通过获取应用程序的Uninstallers文件夹中的卸载脚本来获取已安装应用程序的列表.我希望它与目录无关,所以我得到了当前目录
如果文件存在,我的代码工作正常,但是当它不存在时,它会崩溃我的问题
您尚未指定所看到的结果,因此您的问题很难诊断.但我可以看到一些可能的问题:
Path.Combine如果其参数包含路径中无效的字符,则可以抛出异常.您还没有Path.Combine在try-catch块中包装您的调用.File.Exists或Directory.Exists
调用来检查它,而不是依赖于异常.编辑:在其他地方阅读你的回复后,我看到另一个问题:
//Removes file extesion "-del "
installname.Remove(0, 5);
Run Code Online (Sandbox Code Playgroud)
这不符合你的想法.您需要将该行的结果分配回installName:
installname = installname.Remove(0, 5);
Run Code Online (Sandbox Code Playgroud)
我还担心你期望一个指令和路径以某种方式组合到你的第三个命令行参数中.如果你这样调用你的应用程序:
myapp.exe foo bar -del "C:\myfile.txt"
Run Code Online (Sandbox Code Playgroud)
然后您的命令行参数将如下所示:
args[0] // foo
args[1] // bar
args[2] // -del
args[3] // C:\myfile.txt
Run Code Online (Sandbox Code Playgroud)
换句话说," - del"和您的文件路径将位于不同的参数中.
| 归档时间: |
|
| 查看次数: |
3115 次 |
| 最近记录: |