using System; using System.IO;class Test { public static void Main() { try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("TestFile.txt")) { String line; // Read and display lines from the file until the end of // the file is reached. while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { // Let the user know what went wrong. Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } } }
类似 游标读取,不会把文件都加载到内存
可以MSDN到这两个类,微软的代码很清楚
TextReader 没用过,可以说下简单的使用方法?
using System.IO;class Test
{
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
这是MSDN里的方法
using System.IO;class TextRW
{
static void Main()
{
TextWriter stringWriter = new StringWriter();
using(TextWriter streamWriter =
new StreamWriter("InvalidPathChars.txt"))
{
WriteText(stringWriter);
WriteText(streamWriter);
} TextReader stringReader =
new StringReader(stringWriter.ToString());
using(TextReader streamReader =
new StreamReader("InvalidPathChars.txt"))
{
ReadText(stringReader);
ReadText(streamReader);
}
} static void WriteText(TextWriter textWriter)
{
textWriter.Write("Invalid file path characters are: ");
textWriter.Write(Path.InvalidPathChars);
textWriter.Write('.');
} static void ReadText(TextReader textReader)
{
Console.WriteLine("From {0} - {1}",
textReader.GetType().Name, textReader.ReadToEnd());
}
}