C# 可以使用的 .Net 类库之庞大,不得不感慨一下。对于读取文件这一部分,可以使用的方法很多,特将想到和看到的方法收集在此,用到时可以查一查,温习一下。
以文本文件为例,可以有多种方法。
方法一:System.IO.File.ReadAllText
string content = System.IO.File.ReadAllText(fn);
方法二:Stream
Stream stream = File.OpenRead(fn);
int bytesToRead = 1024;
int bytesRead = 0;
byte[] buffer = new byte [bytesToRead];
// Fill up the buffer repeatedly until we reach the end of file
do {
bytesRead = stream.Read(buffer, 0, bytesToRead);
Console.Write(Encoding.ASCII.GetChars(buffer,0, bytesRead));
} while (bytesToRead == bytesRead);
stream.Close( );
方法三:TextReader
TextReader reader = File.OpenText(fn);
string line;
// Read a line at a time until we reach the end of file
while (reader.Peek() != -1) {
line = reader.ReadLine();
Console.WriteLine(line);
}
reader.Close();
方法四:StreamReader
StreamReader sr = new StreamReader(fn);
string content = sr.ReadToEnd();
Console.WriteLine(content);
sr.Close();
// You should call Dispose on 'reader' here, too.
sr.Dispose();
至于二进制文件,有 BinaryReader/BinaryWriter,当然用 FileStream 也可以。
其他的方法或内容待以后不断补充。