C#StreamReader类用于从流中读取字符串。它继承了TextReader类。它提供Read()和ReadLine()方法从流中读取数据。
C#StreamReader示例读取一行
让我们看一下StreamReader类的简单示例,该类从文件中读取一行数据。
using System;
using System.IO;
public class StreamReaderExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\output.txt", FileMode.OpenOrCreate);
StreamReader s = new StreamReader(f);
string line=s.ReadLine();
Console.WriteLine(line);
s.Close();
f.Close();
}
}
输出:
Hello C#
C#StreamReader示例读取所有行
using System;
using System.IO;
public class StreamReaderExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\a.txt", FileMode.OpenOrCreate);
StreamReader s = new StreamReader(f);
string line = "";
while ((line = s.ReadLine()) != null)
{
Console.WriteLine(line);
}
s.Close();
f.Close();
}
}
【C# StreamReader用法】输出:
Hello C#
this is file handling