文本讀取和寫入流StreamReader和StreamWriter
語法格式:
StreamReader reader = new StreamReader(@"C:\Users\Administrator\Desktop.txt");
也可以這樣寫:
string sourceFile = @"C:\Users\Administrator\Desktop.txt";
StreamReader reader = new StreamReader(sourceFile);
打開一個(gè)文本讀取流:
.StreamReader?reader?=?new?StreamReader(@"C:\Users\Administrator\Desktop.txt");
FileInfo myFile = new FileInfo(sourceFile);
myFile.OpenText();//打開一個(gè)文本讀取流:
流適合處理大型文件,或者大型文本。
StreamReader?reader?=?new?StreamReader(@"C:\Users\Administrator\Desktop.txt");
reader.ReadLine();//讀取一行
如果要讀取一行,并且把這一行輸出,可以這么寫:
string Line = reader.ReadLine();
Console.WriteLine(Line);
reader.Close();//關(guān)閉流
如果要把所有的文本都讀取出來,可以利用for循環(huán):
string?sourceFile?=?@"C:\Users\Administrator\Desktop.txt";
StreamReader?reader?=?new?StreamReader(sourceFile);
string Line = null;
while ((Line = reader.ReadLine()) != null)
{
? ? ? ? Console.WriteLine(Line);
}
reader.Close();

把一個(gè)文件內(nèi)容復(fù)制,并且在重新創(chuàng)建一個(gè)文件出來:
string sourceFile = @"C:\Users\Administrator\Desktop\C#.txt";//C#.txt是源文件
string destinationFile = @"C:\Users\Administrator\Desktop\C++.txt";//C++.txt是目標(biāo)文件
StreamReader reader = new StreamReader(sourceFile);//創(chuàng)建reader
StreamWriter writer = new StreamWriter(destinationFile);//創(chuàng)建writer
string Line = null;
while ((Line = reader.ReadLine()) != null)
{
? ? ? ? ?writer.WriteLine(Line);//邊讀邊寫
}
writer.Close();
reader.Close();
Console.ReadKey();