早教吧 育儿知识 作业答案 考试题库 百科 知识分享

我是一个C#的初学者,usingSystem;usingSystem.IO;\x05\x05\x05publicclassExample{\x05publicstaticvoidMain(){StreamReadersr=null;\x05try{sr=File.OpenText("d:\\csarp\\test.txt");strings;while(sr.Peek()!=-1){s=sr.ReadLine();//可能

题目详情
我是一个C#的初学者,
using System;
using System.IO; \x05\x05\x05
public class Example
{ \x05public static void Main()
{ StreamReader sr=null;\x05
try
{sr=File.OpenText("d:\\csarp\\test.txt");
string s;
while(sr.Peek()!=-1)
{ s=sr.ReadLine(); //可能产生异常
Console.WriteLine(s); }
}
catch(DirectoryNotFoundException e)\x05
{ Console.WriteLine(e.Message); }
catch(FileNotFoundException e)\x05\x05\x05
{ Console.WriteLine("文件"+e.FileName
\x05\x05\x05\x05\x05\x05+"未被发现"); }
catch(Exception e)\x05 //其他所有异常
{Console.WriteLine("处理失败:{0}",e.Message);}
finally
{ if(sr!=null) sr.Close(); }
}
}
其中 StreamReader,sr.Peek()!=-1,s=sr.ReadLine(),DirectoryNotFoundException,e.Message,e.FileName这些语句都是什么意思啊,请尽量用相对白话一些语言解释,
▼优质解答
答案和解析
StreamReader:读取文件里的字符的类
sr.Peek()!=-1:读取下一个字符正常,如果读取异常就是==-1,异常就跳出while循环
s=sr.ReadLine():读取一行字符并赋值给s.
DirectoryNotFoundException:当找不到文件或目录的一部分时所引发的异常
e.Message:上述异常的信息
e.FileName:有上述异常时的文件名,比如这里要打开d:\\csarp\\test.txt,如果文件不存在就会报异常,FileName就是d:\\csarp\\test.txt.