Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read huge file line by line in c# [duplicate]

Tags:

c#

file-read

I have huge files in c# (more than 300 MB). I need effiecent way to read the file line by line because once I try to read it it takes more than 30 minutes while the target time is around 3 minutes. I tried File.ReadAllBytes which reads the files successfully and very fast and load it to the string. But after that it takes very long time to process the string line by line. Is there better way or faster way to do so.

Thank in advance.

like image 291
Abo Ahmed Avatar asked Jan 28 '26 14:01

Abo Ahmed


1 Answers

You can use File.ReadLines, it will enumerate through lines of file:

var lines = File.ReadLines(path);

foreach(var line in lines)
{
    // do your logic here
}

It will not load file at the first line. It will load it while looping through lines, so it's better way to read bigger files, than loading it at once.

MSDN says in description of File.ReadLines

Remarks The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.

like image 163
Kamil Budziewski Avatar answered Jan 31 '26 02:01

Kamil Budziewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!