我有一定的要求。当当前代码行抛出异常时,我想移至下一行
bar foo
有时FileStream fs = new FileStream("D:/temp/product.xml", FileMode.Open, FileAccess.Read);
驱动器没有D:/
文件,它抛出xml
并将控制权跳出了范围。但是在下一行中,我想检查另一个位置
FileNotFoundException
如何解决此问题?
答案 0 :(得分:6)
使用防御性检查,并在实际访问文件之前先使用File.Exists(String)
方法检查文件是否存在。同样,在任何可能的地方,我们都应该使用防御检查而不是异常处理,因为异常处理是一项昂贵的操作。 How expensive are exceptions in C#?
最后,您可以将其完全包装在try .. catch
块中,以确保捕获任何其他异常并记录它们。
try
{
if (File.Exists("D:/temp/product.xml"))
{
FileStream fs = new FileStream("D:/temp/product.xml", FileMode.Open, FileAccess.Read);
}
else
{
// check another location
}
}
catch (Exception ex)
{
// perform logging
}
答案 1 :(得分:5)
您需要做的就是将代码包装在try-catch块中,例如:
FileStream fs = null;
try
{
fs = new FileStream("D:/temp/product.xml", FileMode.Open, FileAccess.Read);
}
catch (FileNotFoundException e)
{
// Retry another file,
}
如果重试也可能失败,则还必须将其包装。
(顺便说一句,拉胡尔的答案更好,更容易)
要在循环中使用它:
FileSystem fs = null;
foreach (var file in files) // files contains the file paths
{
// Solution #1
try
{
fs = new FileStream(file, FileMode.Open, FileAccess.Read);
break;
}
catch (FileNotFoundException e) { }
// Or you can use File.Exists as per Rahul's answer
// Solution #2
if (File.Exists(file))
{
fs = new FileStream(file, FileMode.Open, FileAccess.Read);
break;
}
}
答案 2 :(得分:2)
不要使用异常来检查文件是否存在,而是通过File.Exists检查文件是否存在:
string defaultPath = "D:/temp/product.xml";
string alternativePath = "//letp.rf.servername.com/products/product.xml";
string path = File.Exists(defaultPath) ? defaultPath : alternativePath;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
如果要在没有找到第二条路径的情况下检查另一条路径,则可能要对路径数组使用以下方法。这样,您就可以完全灵活地选择要检查的路径。
string[] paths = new string[] { @"C:\first\path\product.xml", @"C:\second\path\product.xml", @"C:\third\path\product.xml"};
string path = paths.FirstOrDefault(p => File.Exists(p));
if(path == null)
{
Console.WriteLine("None of the files exists!");
}
else
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
}
答案 3 :(得分:1)
只需使用try
和catch
并循环:
foreach (var file in files)
{
try
{
FileStream fs = new FileStream(file , FileMode.Open, FileAccess.Read);
}
catch(Exception ex)
{}
}