The most efficient way to read a file

I have a file that contains a certain number of lines of fixed length having some numbers. I need to read each line to get this number and process them and write to a file. Since I need to read every line, as the number of lines increases, it becomes laborious.

Is there an efficient way to read every line of a file? I am using C #.

+5
source share
4 answers

File.ReadLines (.NET 4.0+) is probably the most memory efficient way.

It returns a value IEnumerable<string>indicating that the lines will be read lazily in a streaming manner.

, , StreamReader .

+14

O (n). , , , .

0

, , : http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx

    //Declare a new file and give it the path to your file
    FileInfo fi1 = new FileInfo(path);

    //Open the file and read the text
    using (StreamReader sr = fi1.OpenText()) 
    {
        string s = "";
        // Loop through each line
        while ((s = sr.ReadLine()) != null) 
        {
            //Here is where you handle your row in the file
            Console.WriteLine(s);
        }
    }
0

, , . , 4 . . , - - . . ( ) ; , , .

, :

  • Try organizing shorter files. It looks like you're processing log files or something like that - using your program more often can help at least provide better performance.

  • Change the way data is stored. Again, I understand that the file comes from some external source, but maybe you can organize a task that periodically converts the raw file into something that you can read faster.

Good luck.

0
source

All Articles