c# streamreader
类用于从流中读取字符串。它继承自textreader
类,它提供read()
和readline()
方法从流中读取数据。
下面来看看一个streamreader
类的简单例子,它从文件中读取一行数据。
using system;
using system.io;
public class streamreaderexample
{
public static void main(string[] args)
{
filestream f = new filestream("e:\\myoutput.txt", filemode.openorcreate);
streamreader s = new streamreader(f);
string line = s.readline();
console.writeline(line);
string line2 = s.readline();
console.writeline(line2);
s.close();
f.close();
}
}
假设e:\myoutput.txt文件的内容如下 -
this is line 1
this is line 2
this is line 3
this is line 4
执行上面示例代码,得到以下输出结果 -
this is line 1
this is line 2
下面代码演示如何使用 streamreader
来读取文件:myoutput.txt中的所有行内容 -
using system;
using system.io;
public class streamreaderexample
{
public static void main(string[] args)
{
filestream f = new filestream("e:\\myoutput.txt", filemode.openorcreate);
streamreader s = new streamreader(f);
string line = "";
while ((line = s.readline()) != null)
{
console.writeline(line);
}
s.close();
f.close();
}
}
执行上面示例代码,得到以下输出结果 -
this is line 1
this is line 2
this is line 3
this is line 4