C# Can';t在string line=reader.ReadLine()上访问读卡器;
如果找不到该文件,C# Can';t在string line=reader.ReadLine()上访问读卡器;,c#,exception,C#,Exception,如果找不到该文件,File.OpenText将引发异常。我不确定为什么每次都抛出异常-几乎可以肯定地删除它 捕获异常并编写消息,但不会在此处停止执行。当您到达reader.ReadLine()reader时,null也从未被实例化过。这就是为什么会出现NullReferenceException。我怀疑你想在失败后再回来 if (Easy) { try { reader = File.OpenText(@"../../TxtFiles/eneral_Easy.tx
File.OpenText
将引发异常。我不确定为什么每次都抛出异常-几乎可以肯定地删除它
捕获异常并编写消息,但不会在此处停止执行。当您到达reader.ReadLine()
reader
时,null
也从未被实例化过。这就是为什么会出现NullReferenceException
。我怀疑你想在失败后再回来
if (Easy)
{
try
{
reader = File.OpenText(@"../../TxtFiles/eneral_Easy.txt");
throw new FileNotFoundException();
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Kan het bestand General_Easy.txt niet vinden!" + ex.Message);
}
}
else
{
reader = File.OpenText(@"../../TxtFiles/General_Hard.txt");
}
string line = reader.ReadLine();
while (line != null)
{
questionList.Add(line);
line = reader.ReadLine();
}
reader.Close();
NumberOfQuestions = questionList.Count;
上面的代码将始终引发异常,无论文件是否实际读入
如果您想在找不到问题文件时将消息转储到控制台,您可以将异常和堆栈跟踪转储到控制台,而不必担心try/catch,让程序崩溃
但是,如果您希望实现一些功能,在这些功能中,您可以设计程序来处理此类异常并进行恢复,您可以执行以下操作:
try
{
reader = File.OpenText(@"../../TxtFiles/eneral_Easy.txt");
throw new FileNotFoundException();
}
问题是什么?为什么在打开文件后引发异常?如果出现错误,请粘贴错误的整个文本。当你的代码运行时,你期望发生什么?@CharlesMager我是个初学者,所以我可能做错了什么。如果找不到文件,我想在控制台中显示一条消息。我得到了一个NullReferenceException。谢谢你的帮助!
try
{
reader = File.OpenText(@"../../TxtFiles/eneral_Easy.txt");
throw new FileNotFoundException();
}
try
{
reader = File.OpenText(@"../../TxtFiles/eneral_Easy.txt");
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Kan het bestand General_Easy.txt niet vinden!" + ex.Message);
var suggestedPath = /* logic to get possible path from another source */
reader = File.OpenText(path); // Will throw again if fails
}