sloppycode.net
Optimum textfile reading in C#
Reading ascii text files fast.
Home
›
Code snippets
›
C#
›
Optimum textfile reading in C#
This example from 2005 reads an 80mb text file in 2 seconds on an AMD 64 2.2ghz, 1gb ram, SATA 10k rpm/s machine (a fast machine in 2005!). This example will be expanded upon in the coming months to include things I discovered from the 'Statmagic' library I created (a log reader API).
Note: the method listed will not reliably read binary files in (or infact unicode), as it uses a char array not a byte array
.
private int bufferSize = 16384; private void readFile(string filename) { FileInfo fileInfo = new FileInfo(filename); FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read); StreamReader streamReader = new StreamReader(fileStream); // Reduce the buffer to fit the filesize, if the buffer is less than the file if ( (int) fileInfo.Length < this.bufferSize ) this.bufferSize = (int) fileInfo.Length; char[] fileContents = new char[this.bufferSize]; int bytesRead = streamReader.Read(fileContents, 0, this.bufferSize ); // Can't do much with 0 bytes if ( bytesRead == 0 ) throw new Exception("File is 0 bytes"); StringBuilder stringBuilder = new StringBuilder(); while( bytesRead > 0 ) { stringBuilder.Append(fileContents); bytesRead = streamReader.Read( fileContents, 0, bufferSize ); } streamReader.Close(); fileStream.Close(); }
{Name}
Says:
{Date}
{Text}
› Home
› C#
› Snippets
› Articles
› Tools
› Taglines
› ASP
› Dictionary Object
› FSO
› Unix cheat sheet
› Gaming
› CSS
› Yak
› Umbraco
› About
› Contact
› Privacy
› Projects
› Search
› Sitemap
Buy on Amazon
Buy on Amazon
Buy on Amazon
Buy on Amazon