2015-01-03 99 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

一個尋求花費**遠遠超過拋出異常的成本。 –