StreamReader是一個用于讀取文本文件的類,它可以一次讀取一個字符或一行字符。以下是一些使用StreamReader讀取文件的技巧:
using (StreamReader sr = new StreamReader("file.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
using (StreamReader sr = new StreamReader("file.txt"))
{
int c;
while ((c = sr.Read()) != -1)
{
Console.Write((char)c);
}
}
using (StreamReader sr = new StreamReader("file.txt"))
{
string content = sr.ReadToEnd();
Console.WriteLine(content);
}
using (StreamReader sr = new StreamReader("file.txt"))
{
while (sr.Peek() >= 0)
{
int c = sr.Read();
Console.Write((char)c);
}
}
using (StreamReader sr = new StreamReader("file.txt", Encoding.UTF8))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
以上是一些使用StreamReader讀取文件的技巧,可以根據需要選擇合適的方法來讀取文件內容。