C# System.IO.FileNotFound Exception

本文关键字:Exception FileNotFound IO System | 更新日期: 2023-09-27 18:18:13

这是我的代码。如果我输入一个存在的文件,一切都能正常工作。但是,每当我输入一个不存在的文件时,就会得到"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.
}
}

C# System.IO.FileNotFound Exception

你得到这个异常可能是因为这一行:

var reader = new StreamReader (p);

在检查文件是否存在之前执行它。如果你不想要那个异常,你应该先调用检查file是否存在的方法。