Search code examples
c#.netoptimization.net-2.0io

Reading from file not fast enough, how would I speed it up?


This is the way I read file:

    public static string readFile(string path)
    {
        StringBuilder stringFromFile = new StringBuilder();
        StreamReader SR;
        string S;
        SR = File.OpenText(path);
        S = SR.ReadLine();
        while (S != null)
        {
            stringFromFile.Append(SR.ReadLine());
        }
        SR.Close();
        return stringFromFile.ToString();
    }

The problem is it so long (the .txt file is about 2.5 megs). Took over 5 minutes. Is there a better way?

Solution taken

    public static string readFile(string path)
    {

       return File.ReadAllText(path);

    }

Took less than 1 second... :)


Solution

  • Leaving aside the horrible variable names and the lack of a using statement (you won't close the file if there are any exceptions) that should be okay, and certainly shouldn't take 5 minutes to read 2.5 megs.

    Where does the file live? Is it on a flaky network share?

    By the way, the only difference between what you're doing and using File.ReadAllText is that you're losing line breaks. Is this deliberate? How long does ReadAllText take?