2015-10-17 78 views
-4

這是我的代碼。如果我輸入存在的文件,一切正常。但是,每當我輸入一個不存在的文件,我得到的「System.IO.FileNotFound異常錯誤消息。我不知道這是爲什麼。有方向對我有什麼在評論做。C#System.IO.FileNotFound異常

感謝

using System; 
`using System.IO; 

namespace IntroCS 
{ 
class SumFile 
{ 
/** 
* Program starts here 
*/ 
static void Main() 
{ 
String prompt = UIF.PromptLine ("Enter name of file to print: "); 
var sr = PromptFile (prompt); 
if (sr != null){ 
Console.WriteLine("The sum is {0}", CalcSum(sr)); 
} 
else{ 
Console.WriteLine ("You give up!"); 
} 
} 
// Declare and get a StreamReader object here, from PromtpFile() 
// Test if the StreamReader is null. If it is not null, calculate 
// the sum of numbers in that StreamReader. Otherwise, print 
// "You give up!" 

static StreamReader PromptFile (string prompt) 
{ 
String p = UIF.PromptLine ("Enter the name of file to print: "); 
var reader = new StreamReader (p); 
if (File.Exists (p)) { 
return reader; 
} else { 
return null; 
} 
} 
// Print out the prompt and read the path. Use UIF/UI function if you 
// want 
// Check if the path is empty string. If yes, you should return null 
// If path is not empty string, your program should keep prompting 
// for user input until a valid path or empty string is received 
// To test if a file path is valid, use File.Exists(string path) 
// function, which returns a boolean variable telling you if that 
// path is valid or not. 
// If the path is valid, you should return a object of StreamReader 
// of that path. Otherwise, return null. 

// This function take a valid StreamReader object as argument, read the 
// all the lines of the file, convert them to integer, and calculate 
// the sum of them 
static int CalcSum(StreamReader sr) 
{ 
int n = 0; 
while (!sr.EndOfStream) { 
string sVal = sr.ReadLine().Trim(); 
if (sVal.Length > 0) { 
n += int.Parse (sVal); 
} 

} 
return n; 
} 
// Declare a integer variable for calculating the sum. 
// and initialize it to 0 
// Read the entire file till the end of the stream. Use 
// sr.EndOfStream to tell if you have reached the end of file 
// Close the StreamReader object and return the sum of all numbers 
// in that file. 
} 
} 

回答

3

你得到這個異常可能是由於該行:

var reader = new StreamReader (p); 

你檢查之前,如果文件存在執行它。如果你不想讓你的異常應該調用哪些檢查方法。如果文件先存在。

+0

謝謝你擺脫了錯誤信息。我沒有理解這一點。 –

+0

@NickPredey:你可以考慮接受答案,如果它對你有幫助。 –

+0

我會的。由於我剛剛做了一個帳戶,我必須等待。 –