How to get text files faster than StreamReader.ReadToEnd()

aewarnick

Well-known member
Joined
Jan 29, 2003
Messages
1,031
I was told that ReadToEnd() was slower than if you put the whole thing into a byte[] and went from there. I think I am having problems, because my method is so much slower than ReadToEnd() is:

C#:
public static object Read(ref string path)
		{
			string g="";
			if(File.Exists(path))
			{
				Stream F=new FileStream(path, FileMode.Open, FileAccess.Read);
				byte[]b=new Byte[F.Length];
				F.Read(b, 0, Convert.ToInt32(F.Length));

				for(int i=0; i< b.Length; i++)
				{
					if(b[i]==0) break;
					g+=(char)b[i];
				}
			//StreamReader s=new StreamReader(path);
			//string g= s.ReadToEnd();
			//s.Close();
MessageBox.Show(g);
				F.Close();
			}
			return g;
		}

Why is mine so slow?
 
Last edited by a moderator:
You are concatenating a string each time, which means completely recreating it for every byte in your file. To instantly convert a byte array in to a string, look at System.Text.Encoding.ASCII.GetString().
 
Do I have to write that whole thing all the time? Why cant I put in up at the top with all the other usings?
 
Back
Top