简介
可以通过此类读取计算机上的文本文件内容。
在程序的Debug文件夹下面新建一个文本文件,命名为test.txt,在里面输入hello world!
构造函数
StreamReader (Stream stream,Encoding encoding)
使用流对象stream以及编码方式encoding来创建一个读取流streamReader。
static void Main(string[] args){FileStream fs=new FileStream("test.txt",FileMode.Open,FileAccess.ReadWrite);StreamReader sr=new StreamReader(fs,Encoding.UTF8);Console.ReadKey();}
StreamReader (string path, Encoding encoding)
通过文件路径path,以及编码方式encoding来创建一个读取流streamReader。
static void Main(string[] args)
{StreamReader sr = new StreamReader("test.txt", Encoding.UTF8);Console.ReadKey();
}
常用属性
CurrentEncoding
获取streamReader实例的当前文本编码格式。
static void Main(string[] args)
{StreamReader sr = new StreamReader("test.txt");Console.WriteLine("sr的编码方式为:"+sr.CurrentEncoding);StreamReader sr1 = new StreamReader("test.txt", Encoding.ASCII);Console.WriteLine("sr1的编码方式为:" + sr1.CurrentEncoding);Console.ReadKey();
}运行结果:
sr的编码方式为:System.Text.UTF8Encoding
sr1的编码方式为:System.Text.ASCIIEncoding
可以看到,创建实例时,如果不指定编码格式,那么会默认为utf8格式。如果想要指定为其他格式,则需要在创建实例时,提供对应的参数。
EndOfStream
判断streamReader的位置是否处于末尾,如果是,返回true;否则,返回false。在读取时,可以根据此属性来判断是否已经把全部内容读完。
常用方法
Close()
当使用完streamReader实例以后,调用Close()方法,可以关闭读取流,并且释放它所占用的资源。
DiscardBufferedData()
丢弃输入寄存器中的数据,一般读取文本文件内容前可以先执行此方法,可以避免输入寄存器原有的数据,混合文本文件的内容一起被读取。
Peek()
返回读取流下一个读取字符的Ascii码,但不使用下一个字符,如果当前已经时最后一个字符了,那么返回-1。
Read ()
读取一个字符,返回该字符对应的Ascii码,并且把streamReader实例的位置增加1,如果没有可以读取的字符,那么返回-1。
static void Main(string[] args)
{StreamReader sr = new StreamReader("test.txt");Console.WriteLine("下一个字符的ascii码是:"+sr.Peek());Console.WriteLine("读取的当前字符ascii码是:"+sr.Read());Console.WriteLine("下一个字符的ascii码是:" + sr.Peek());sr.Close();Console.ReadKey();
}
Read (char[] buffer, int index, int count)
从当前streamReader实例中读取从index开始的count个字符到字符数组buffer中。
static void Main(string[] args)
{char[] array = new char[5];StreamReader sr = new StreamReader("test.txt");sr.Read(array, 0, 5);foreach (char c in array){Console.WriteLine(c);}sr.Close();Console.ReadKey();
}运行结果:
h
e
l
l
o
ReadLine()
从streamReader实例中读取一行并返回,然后提升流的当前位置。
打开debug文件夹的test.txt文件,然后在hello world!下面再加一行,输入i love c#
static void Main(string[] args)
{StreamReader sr = new StreamReader("test.txt");Console.WriteLine("读取一行:"+ sr.ReadLine());Console.WriteLine("读取一行:" + sr.ReadLine());sr.Close();Console.ReadKey();
}运行结果:
读取一行:hello world!
读取一行:i love c#
ReadToEnd()
读取streamReader实例中的所有内容,并返回string。
static void Main(string[] args)
{StreamReader sr = new StreamReader("test.txt");string str=sr.ReadToEnd();Console.WriteLine(str);sr.Close();Console.ReadKey();
}运行结果:
hello world!
i love c#