简体   繁体   English

C# System.IO.FileNotFound 异常

[英]C# System.IO.FileNotFound Exception

This is my code.这是我的代码。 If I enter in a file that exists, everything works correctly.如果我输入一个存在的文件,则一切正常。 However, whenever I enter a file that does not exist, I get the "System.IO.FileNotFound exception error message. I'm not sure why this is. There are directions for what I have to do in the comments.但是,每当我输入一个不存在的文件时,我都会收到“System.IO.FileNotFound 异常错误消息。我不确定为什么会这样。在评论中有我必须做的说明。

Thanks谢谢

 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.
}
}

You get that exception probably due to this line:您可能由于这一行而得到该异常:

var reader = new StreamReader (p);

you execute it before checking if file exists.在检查文件是否存在之前执行它。 If you don't want that exception you should call the method which checks if file exists first.如果您不想要该异常,您应该首先调用检查文件是否存在的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM