1

different ways to read all the lines of a text file

Free lines C# 1 revisions 117 a year ago a year ago
/* Reading the entire file into a single string using a StreamReader ReadToEnd() method */
using (StreamReader sr = File.OpenText(fileName))
{
        string s = sr.ReadToEnd();
        //you have to process the string
}
/* Reading the entire file into a single StringBuilder object using a StreamReader ReadToEnd() method */
using (StreamReader sr = File.OpenText(fileName))
{
        StringBuilder sb = new StringBuilder();
        sb.Append(sr.ReadToEnd());
        //you have to process the string
}
/* Reading each line into a string using StreamReader ReadLine() method */
/* this one is the fastest when tested */
using (StreamReader sr = File.OpenText(fileName))
{
        string s = String.Empty;
        while ((s = sr.ReadLine()) != null) {}
}
/* Reading each line into a string using a BufferedStream */
using (FileStream fs = File.Open(fileName, ..... ))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
        string s;
        while ((s = sr.ReadLine()) != null) {}
}
/* Reading each line into a string using a BufferedStream with a preset buffer size equal to the size of the biggest line */
using (FileStream fs = File.Open(fileName, ..... ))
using (BufferedStream bs = new BufferedStream(fs, System.Text.ASCIIEncoding.Unicode.GetByteCount(g)))
using (StreamReader sr = new StreamReader(bs))
{
    string s;
    while ((s = sr.ReadLine()) != null) {}
}
/* Reading each line into a StringBuilder object using StreamReader ReadLine() method. */
using (StreamReader sr = File.OpenText(fileName))
{
    StringBuilder sb = new StringBuilder();
    while (sb.Append(sr.ReadLine()).Length > 0) {}
}
/* Reading each line into a StringBuilder object with its size preset and equal to the size of the biggest line */
using (StreamReader sr = File.OpenText(fileName))
{
    StringBuilder sb = new StringBuilder(g.Length);
    while (sb.Append(sr.ReadLine()).Length > 0) {}
}
/* Reading each line into a pre-allocated string array object. */
AllLines = new string[MAX];
using (StreamReader sr = File.OpenText(fileName))
{
    int x = 0;
    while (!sr.EndOfStream)
    {
        AllLines[x] = sr.ReadLine();
        x += 1;
    }
}
/* Reading the entire file into a string array object using the .Net ReadAllLines() method. */
AllLines = new string[MAX];
AllLines = File.ReadAllLines(fileName);

title says it all