我想要最高效的方式来读取和解析文件。
是否可以在 .NET 中读取文件,但不能将整个文件加载到内存中?即在我解析每一行的内容时逐行加载文件?
XmlTextReader 是将整个文件加载到内存中,还是在读取文件时将文件流式传输到内存中?
最佳答案
您可以使用 StreamReader 类的 ReadLine 方法:
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
}
file.Close();
对于 XML 文件,我会使用 XMLTextReader。看到这个 article on Dr. Dobb's Journal :
" 使用 C# 解析 .NET 中的 XML 文件: .NET 中有五种不同的解析技术,每一种都有自己的优势"
关于.net - 在 .NET 中读取和解析文件 - Performance For Hire,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/247066/