本文介绍了按块读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用C#.net

如何通过块来读取文本块,块由新行字符分隔。



块大小不固定,所以我无法使用StreamReader的ReadBlock方法。

有没有其他方法可以获取数据由于它是由新的行字符分隔的块。因此,您可以使用一个:

  using(var reader = File.OpenText(foo.txt))
{
string line; $(b)
while((line = reader.ReadLine())!= null)
{
//用
}

$ b

此方法逐行读取文本文件(其中Environment.NewLine用作行分隔符)并仅包含当前行加载到内存中,所以它可以用来读取非常大的文件。

如果你只是想加载一个小文本文件的所有行内存中,你也可以使用方法:

  string [] lines = File.ReadAllLines(foo.txt); 
// lines数组将包含所有行
//不要在大文件中使用这个方法
//将整个内容加载到内存


I am using C#.net

How can read a text file block by block, the block is separated by new line character.

Block size is not fixed, so i am not able to use ReadBlock method of StreamReader.

Is there any ohter method for getting the data block by block as it is separated by new line character.

解决方案

You could use a StreamReader:

using (var reader = File.OpenText("foo.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // do something with the line
    }
}

This method reads the text file line by line (where Environment.NewLine is used as line separator) and has only the current line loaded in memory at once so it could be used to read very large files.

If you just want to load all the lines of a small text file in memory you could also use the ReadAllLines method:

string[] lines = File.ReadAllLines("foo.txt");
// the lines array will contain all the lines
// don't use this method with large files
// as it loads the entire contents into memory

这篇关于按块读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 12:03
查看更多