StreamReader’s in .NET

May 24, 2007

Generally no one notices that the StreamReader in .NET has a problem with ReadLine() function. The function is expected to read a line which has “\r\n” at the end, but it reads up to “\r”.  Carriage returns are are treated as new-line characters in .NET StreamReader.

Here is a possible implemention of good “ReadLine()” function using the StreamReader itself.

public string ReadLine(){

StreamReader sr = new StreamReader(“some_test_file.csv”);

StringBuilder sb = new StringBuilder();char[] ch = new char[1];

int state = -1;//FSM code for parsing the \r\n

while (true){

int i = sr.Read();switch (i){

case 13 :

state = 1;

break;case 10:

if (state == 1){ state = 2; }


{ state = 0; }

break;case -1: state = 2;


default:state = 0;


if (state == 2) break;}

return sb.ToString();}

In this code the care is taken for taking “\r\n” as new-line and not “\r”.



Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: