【发布时间】:2008-10-29 14:44:52
【问题描述】:
我想要读取和解析文件的最高效方式。
是否可以在 .NET 中读取文件,但不能将整个文件加载到内存中?即在我解析每一行的内容时逐行加载文件?
XmlTextReader 是将整个文件加载到内存中,还是在读取文件时将文件流式传输到内存中?
【问题讨论】:
-
最佳性能 = 最佳性能
标签: .net performance file
我想要读取和解析文件的最高效方式。
是否可以在 .NET 中读取文件,但不能将整个文件加载到内存中?即在我解析每一行的内容时逐行加载文件?
XmlTextReader 是将整个文件加载到内存中,还是在读取文件时将文件流式传输到内存中?
【问题讨论】:
标签: .net performance file
您可以使用 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 中有五种不同的解析技术,每一种都有自己的优势”
【讨论】:
XmlTextReader 在流上工作 - 因此它不会读取内存中的整个文件。
【讨论】:
这是我多年来一直在使用的 TextFileReader 类
http://www.dotnet2themax.com/ShowContent.aspx?ID=4ee44d6c-79a9-466d-ab47-56bba526534f
【讨论】:
我不确定 XMLTextReader,但您可以使用 FileReader 对象逐行读取文件。 )
【讨论】:
您可以尝试使用 StreamReader.ReadLine 函数并测试与 FileStream/TextReader 等相比的性能。
【讨论】:
我也不确定 XMLTextReader,但您可以像这样逐行阅读:
Dim theLine as String
Dim fsFile As New FileStream(inputFile, FileMode.Open) 'File Stream for the Input File
Dim fsImport As New FileStream(outputFile, FileMode.OpenOrCreate) 'File Stream for the Output File
Dim srFile As New StreamReader(fsFile) 'Stream Reader for Input File
Dim swfile As New StreamWriter(fsImport) 'Stream Writer for Output File
Do While srFile.Peek <> -1 'Do While it's not the last line of the file
theLine = srFile.ReadLine 'Read the line
Messagebox.Show(theLine, "Line-by-Line!")
Loop
【讨论】:
XmlTextReader 不会将整个文件加载到内存中,它对流进行操作。
所有文件流对象都以“块”的形式读取文件。 您可以指定每次调用(即 m 字节,其中 m 是任何整数 - 可能是长 - 值,或使用文本阅读器,任意长度的单行)带回程序的数据量(即块有多大) ) 出于性能原因,操作系统将在每次读取时缓存 n 个字节(其中 n 部分或全部为 0)。 你完全无法控制 n 的大小,只会让你自己尝试找出它是什么而感到沮丧,因为它会因一千种不同的环境因素而变化。
【讨论】: