我想要以最佳格式阅读和解析文件。
是否可以在.NET中读取文件,但不能将整个文件加载到内存中?即只需在解析每一行的内容时逐行加载文件?
XmlTextReader是否将整个文件加载到内存中,或者在读取文件时将文件流式传输到内存中?
答案 0 :(得分:10)
您可以使用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中提供了五种不同的解析技术,每种技术都有自己的优势”
答案 1 :(得分:1)
XmlTextReader适用于流 - 因此它不会读取内存中的整个文件。
答案 2 :(得分:1)
这是我多年来一直使用的TextFileReader类
http://www.dotnet2themax.com/ShowContent.aspx?ID=4ee44d6c-79a9-466d-ab47-56bba526534f
答案 3 :(得分:0)
我不确定XMLTextReader,但您可以使用FileReader对象逐行读取文件。 )
答案 4 :(得分:0)
您可以尝试使用StreamReader.ReadLine函数并测试与FileStream / TextReader等内容相比的性能。
答案 5 :(得分:0)
我也不确定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
答案 6 :(得分:0)
XmlTextReader不会将整个文件加载到内存中,而是在流上运行。
所有文件流对象都以“块”的形式读取文件。 您可以指定每次调用返回程序的数据量(即块大小)(即m个字节,其中m是任意整数 - 可能是长整数值,或者使用文本阅读器,任意长度的单行) ) 出于性能原因,OS将每次读取缓存n个字节(其中n为0或0)。 你完全无法控制n的大小,只会让自己试图找出它是什么,因为它会因千种不同的环境因素而发生变化。