2015-01-03 292 views
2

我刚刚注册了网站,所以我可能把这个错误。无论如何,我试图使用C#中的try和catch来捕获我的文件,如果它没有找到。这是我目前的代码。重复我自己,我希望程序读取文件,就像它一样 - 但是如果文件没有找到,我希望它给出一个错误,说“无法找到文件”或沿着这些线的东西,而不是简单的只是崩溃。 (我刚刚开始学习C#)C#try and catch

感谢您的帮助!

string file = @"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt"; 
try 
{ 
    file = @"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt"; 
} 
catch 
{ 
    Console.WriteLine("Could not find the file - grades_multiple.txt"); 
}    
//ARRAY for string lines 
string[] Line = new string[6]; 
Line[0] = File.ReadLines(file).Skip(1).Take(1).First(); 
+1

你周围有一个简单的字符串赋值的尝试。不会抛出异常。它可能需要围绕在你的'ReadallLine'语句中,因为这可能由于各种原因而失败。 – Plutonix

回答

3

你应该阅读的尝试捕捉里面的文件,赶上FileNotFoundException,像这样:

var file = @"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt"; 
string[] lines; 
try 
{ 
    lines = File.ReadAllLines(file); 
} 
catch (FileNotFoundException exnotfound) 
{ 
    // file not found exception 
} 
catch (Exception ex) 
{ 
    // handle other exceptions 
} 
+0

辉煌!它完美的工作,我不能完全感谢你:) – Yrneh

0

你需要把是错误try块的内部容易出现的代码。

try 
{ 
    Line[0] = File.ReadLines(file).Skip(1).Take(1).First(); 
} 
catch(Exception ex) 
{ 
    Console.WriteLine("Could not find the file - grades_multiple.txt"); 
} 

顺便说一句,你可以通过检查文件中使用File.Exists method.There无需catch例外存在第一处理这种情况。

0

尝试抓住就不会像这样工作。 您试图捕捉一行代码来更改一个字符串,并且不会更改文件,因此该文件不需要存在,所以它会从不抛出一个异常(在您的情况),它会从来没有赶上它。

您应环绕代码可以出错:File.ReadLines

您的代码会变成这样:

string file = @"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt"; 

//can go wrong 
try 
{ 
    //ARRAY for string lines 
    string[] Line = new string[6]; 
    Line[0] = File.ReadLines(file).Skip(1).Take(1).First(); 
} 
//File.ReadLines is null 
catch 
{ 
    Console.WriteLine("Could not find the file - grades_multiple.txt"); 
} 

我也认为这是更好的做法,如果语句的检查它,而不是当它出现错误时捕捉它:

//if file exists 
if(File.Exists(file)) 
{ 
    //ARRAY for string lines 
    string[] Line = new string[6]; 
    Line[0] = File.ReadLines(file).Skip(1).Take(1).First(); 
} 
//File does not exist 
else 
{ 
    Console.WriteLine("Could not find the file - grades_multiple.txt"); 
} 
0

如果有可能,你应该尝试av oid抛出异常只是为了向用户显示一条消息或者可以轻松测试的条件。这主要是性能考虑因素,因为抛出异常很昂贵。此外,除非您知道该文件相对较小,否则可能会将性能加载到内存中。

以下是有关如何测试条件并处理它的快速原始示例。

void Main() 
{ 
    var filePath ="C:\\TEST.DAT"; 

    if(!File.Exists(filePath)){ DisplayFileNotFoundError(filePath); } 

    try 
    {   
     var lines = GetFileLines(filePath); 
     if(lines == null) { DisplayFileNotFoundError(filePath);} 

     // do work with lines; 
    } 
    catch (Exception ex) 
    { 
     DisplayFileReadException(ex); 
    } 

} 

void DisplayErrorMessageToUser(string filePath) 
{ 
    Console.WriteLine("The file does not exist"); 
} 

void DisplayFileReadException(Exception ex){ 
    Console.WriteLine(ex.Message); 
} 

string[] GetFileLines(string filePath){ 

    if(!File.Exists(filePath)){ return null; } 

    string[] lines; 
    try 
    {   
     lines = File.ReadLines(filePath); 
     return lines; 
    } 
    catch (FileNotFoundException fnf){ 
     Trace.WriteLine(fnf.Message); 
     return null; 
    } 
    catch (Exception ex) 
    { 
     Trace.WriteLine(ex.Message); 
     throw ex; 
    } 
} 

性能测试,FileNotFoundException异常VS File.Exists

void Main() 
{ 
    int max = 100000; 
    long[] feSampling = new long[max]; 
    long[] exSampling = new long[max]; 

    String pathRoot ="C:\\MISSINGFILE.TXT"; 
    String path = null; 

    Stopwatch sw = new Stopwatch(); 
    for (int i = 0; i < max; i++) 
    { 
     path = pathRoot + i.ToString(); 
     sw.Start(); 
     File.Exists(pathRoot); 
     sw.Stop(); 
     feSampling[i] = sw.ElapsedTicks; 

     sw.Reset(); 
    } 

    StreamReader sr = null; 
    sw.Reset(); 
    for (int i = 0; i < max; i++) 
    { 
     path = pathRoot + i.ToString(); 
     try 
     {   
      sw.Start(); 
      sr = File.OpenText(path); 
     } 
     catch (FileNotFoundException) 
     { 
      sw.Stop(); 
      exSampling[i] = sw.ElapsedTicks; 
      sw.Reset(); 

      if(sr != null) { sr.Dispose();} 
     } 
    } 

    Console.WriteLine("Total Samplings Per Case: {0}", max); 
    Console.WriteLine("File.Exists (Ticsk) - Min: {0}, Max: {1}, Mean: {2}", feSampling.Min(), feSampling.Max(), feSampling.Average()); 
    Console.WriteLine("FileNotFoundException (Ticks) - Min: {0}, Max: {1}, Mean: {2}", exSampling.Min(), exSampling.Max(), exSampling.Average()); 

} 
+0

当你在处理磁盘操作时,无论如何你都必须捕获错误,并且与去磁盘的成本相比,异常块的成本是微不足道的。为什么有两个代码路径,当你会做? –

+0

这不是关于异常块的成本,而是抛出异常块本身的成本。在这种情况下,IO操作的大部分成本并不高,因为它是针对主文件表的查找而不是大量的查找。与其他所有事情一样,在选择一种方法时需要考虑许多因素,例如内部驱动器的速度或网络连接存储器,或许更重要的是预计事务的数量。 – AgustinCoder

+0

一个寻求花费**远远超过抛出异常的成本。 –