You gotta love the little things in .NET Framework 2.0: File.ReadAllLines()


I was recently reviewing some samples and I ran across one that made me really appreciate the work we did in BCL in .NET Framework 2.0… it maybe a very trivial thing, but it really improves the code. 


 


The code sample in question looked something like:


 


      if (autoCompleteWordList == null)


      {


        List<String> words = new List<string>();


        FileStream file = new


          FileStream(Server.MapPath(“~/App_Data/words.txt”), FileMode.Open,


          FileAccess.Read);


        StreamReader reader = new StreamReader(file);


        String word;


        while ((word = reader.ReadLine()) != null)


        {


          words.Add(word);


        }


        file.Close();


        autoCompleteWordList = words.ToArray();


        Array.Sort(autoCompleteWordList, new CaseInsensitiveComparer());


      }


 


 


I was able to cut the lines of code by more than 1/2 by using the File.ReadAllLines() method added in .NET Framework 2.0


 


 


      if (autoCompleteWordList == null)


      {


          string[] temp = File.ReadAllLines(Server.MapPath(“~/App_Data/words.txt”));


          Array.Sort(temp, new CaseInsensitiveComparer());


          autoCompleteWordList = temp;


      }


 


 


 


What do you think?  What other timesaving gems have you found in .NET Framework 2.0?


 

Comments (16)

  1. Kris says:

    Python had this kind of functionality. Glad to see it in .NET 2.0

  2. For me, it’s easily String.IsNullOrEmpty

  3. Sean Chase says:

    +1 on String.IsNullOrEmpty

    Also, I’m not sure anything has saved me more time than generics. Especially using Collection<T> in lieu of CollectionBase.

  4. Console.ForegroundColor

  5. Dmitry Shaporenkov says:

    string.ToLower(Upper)Invariant

  6. Themes says:

    It may be much more nice if it returns not string[] but IEnumerator<string>.

    Because with IEnumerator it can fulfill both requirement: read all-at-once strings and read strings one-by-one.

    Consider this scenario:

    foreach( string line in File.ReadAllLines(…) )

    Console.WriteLine(line);

    With current implementation this code will add unneeded memory pressure especially huge for large files. The code is easy to write but performs ugly.

    With my version, where IEnumerable returned, this easy code could performs very well. This could be ReadAllLines implementation. Note that this code fulfill all security/performance/reliability requirements of BCL because of C# iterator and "foreach" nature.

    IEnumerator<string> ReadAllLines(string filename)

    {

    using( StreamReader reader = File.OpenText(filename) )

    {

    while( !reader.AtEndOfStream )

    {

    yield return reader.ReadLine();

    }

    }

    }

    Unfortunately, this idea came to me just now and I did not push to BCL Team it before. I realize that today you cannot adhere this IEnumerator syntax to BCL :-(

  7. Dan McKinley says:

    I think it’s great, it makes writing little apps a lot simpler. Not to rain on your parade, but I do have a "bah humbug" for it.

    Most of the problems I’ve been dealing with at work in the last few months have involved digging developers out of the holes they dig themselves when they assume they can keep everything in memory at once. My initial reaction when I saw this API was mostly panic–here’s yet another way for a scripter to hold on to data he doesn’t need and write an application that doesn’t scale.

    But again, great job in the simple cases.

  8. Rusty Zarse says:

    class CustomResultsClass : Dictionary<string, List<SomeCustomClass>>{}

    that used to take an awful lot of code!

    thankyou , thankyou, thankyou!

  9. Sergio Pereira says:

    I don’t know if this qualifies as a gem (maybe a whole treasure chest), but I’m really happy to see the System.Configuration assembly in .Net 2.0.

    Another very nice little generic class is KeyedCollection<K, T> from the System.Collections.ObjectModel namespace.

  10. Shabazz-Perez says:

    the .Net framework block keeps appearing on my computer when I turnit on, how do you get the thing off!!!

  11. Definitively String.IsNullOrEmpty!

  12. Keith Patrick says:

    For a 2.1 suggestion, a String.IsNullOrTrimmedEmpty would be even better :)

  13. Rc says:

    What about this..

    string[] aa = System.IO.File.OpenText("d:test.txt").ReadToEnd().Split(‘n’);

    just don’t forget to strip the r for the last entry.

  14. Keith Hill says:

    Or how about an overload String.IsNullOrEmpty(StringNullOrEmptyTestOptions.TrimString) or maybe just String.IsNullOrEmpty(bool trimString).

  15. Sheva says:

    Re Keith Hill:

    How about this implementation:

    public seal class String

    {

    public static Boolean IsNullOrEmptyOrBlank(String value)

    {

    return String.IsNullOrEmpty(value) ? true : value.Trim().Length == 0;

    }

    }