The Most Useful .NET Utility Classes Developers Tend To Reinvent Rather Than Reuse

0 comments suggest edit

System.IO.Path

How often do you see code like this to create a file path?

public string GetFullPath(string fileName)
{
  string folder = ConfigurationManager.AppSettings["somefolder"];
  return folder + fileName;
}

Code like this drives me crazy because it is so prone to error. For example, when you set the folder setting, you have to remember to make sure it ends with a slash. Having too many things to remember makes this setup fragile.

Sure, you write some code to ensure that the folder has an ending slash, but I’d rather let someone write that code. For example, Microsoft.

The .NET framework is definitely huge so it can be understandable to miss out on some of the useful utility classes in there that will make your life as a developer easier.

public string GetFullPath(string filename)
{
  string folder = ConfigurationManager.AppSettings["somefolder"];
  return System.IO.Path.Combine(folder, filename);
}

The Path class is certainly well known and probably well used, but is still one of those classes that developers seem to never use to its full potential. For example, how often do you see this?

//make sure folder path ends with slash
string folder = GetFolderPath() + @"\";

Well that’s nice for Windows machines, but our world is changing and someday, you may want your code to run on Linux or, god forbid, a Mac! Instead, you could use this and be safe.

string folder = GetFolderPath() + Path.DirectorySeparatorChar;

That’ll make sure the slash leans in the correct direction based on the platform. Oh, and the next time I see code to parse a file name from a path, I’m going to slap the developer upside the head and mention this method:

string fileName = Path.GetFileName(fullPath);

System.Web.VirtualPathUtility {.clear}

Not knowing and using this class is forgivable because it didn’t exist until .NET 2.0. But now that you are reading this, you have no excuse. One great usage is for converting tilde paths to absolute paths.

Note: The tilde (~) character is called the root operatorin the context of ASP.NET virtual URLs. A little trivia for you.

For example, if you are running an app in a virtual application named “MyApp”, the following:

string path = VirtualPathUtility.ToAbsolutePath("~/Controls/Test.ascx");

Sets path to /MyApp/Controls/Test.ascx. No need to write your own ResolveUrl method.

Some other useful methods (there are many more than these listed)…

Method Description
AppendTrailingSlash Appends a / to the end of the path if none exists already.
Combine Analagous to Path.Combine, but for URLs.
MakeRelative Useful for getting the relative path from one directory to another (was it dot dot slash dot dot slash? Or just dot dot slash?)

System.Web.HttpUtility

This class has a wealth of methods for URL/HTML encoding and decoding. A small sampling…

Method Description
HtmlEncode Converts a string to an HTML encoded string.
HtmlDecode Decodes an HTML encoded string.
UrlEncode Converts a string to a URL encoded string.
UrlDecode Decodes a URL encoded string.

One particular method that is pretty neat in this class is HtmlAttributeEncode. This method is HtmlEncode’s lazy cousin. It does the minimal work to safely encode a string for HTML. For example, given this string:

<p>&</p>

HtmlEncode produces: &lt;p&gt;&amp;&lt;/p&gt;

wherease HtmlAttributeEncode produces: &lt;p>&amp;&lt;/p>

In other words, it only encodes left angle brackets, not the right ones.

System.Environment

This class contains a wealth of information about the current environment in which your code is executing. You can get access to the MachineName, the CommandLine, etc…

However, the one property I would like to get developers to use is a simple one:

//Instead of this
string s = "Blah\r\n";
//do this
string s = "Blah" + Environment.NewLine;

Again, this falls under the case that your code might actually run on a different operating system someday. Might as well acquire good habits now.

What Classes Am I Missing?

No matter how hard I can try, there is no way that I could make a complete list. In .NET 3.0, I’d probably add the new TimeZoneInfo class. What classes do you find extremely useful that are not so well known? Or worse, what classes have functionality that you see developers reinventing the wheel recreating, rather than using the existing class?

Found a typo or error? Suggest an edit! If accepted, your contribution is listed automatically here.

Comments

avatar

64 responses

  1. Avatar for Damien Guard
    Damien Guard June 13th, 2007

    IsNumeric(string something)
    A vague name that doesn't signify whether it considers decimal places or numeric formatting valid. If it does it likely doesn't check for more than one decimal place indicator nor handle European number formats.
    Once IsNumeric'ed caller probably wants to turn it into a number type resulting in a whole second, and likely different, check.
    Just use Double.TryParse and Int.TryParse.
    [)amien

  2. Avatar for M
    M June 13th, 2007

    Another thing I keep running into is programmers wrestling with Ststem.Random to generate file names for temporary files instead of just using
    Path.GetTempFileName()

  3. Avatar for Haacked
    Haacked June 13th, 2007

    @M - Oh, that's a good one!

  4. Avatar for Jon Rowett
    Jon Rowett June 13th, 2007

    is this a typo?
    > string path = VirtualPathUtility.ToAbsolutePath("~/Controls/Test.ascx");
    > ~/MyApp/Controls/Test.ascx

  5. Avatar for Haacked
    Haacked June 13th, 2007

    @Jon - Yep. Fixed. Thanks!

  6. Avatar for Mads Kristensen
    Mads Kristensen June 13th, 2007

    Good one Phil. I use the VirtualPathUtility class all the time, but don't see it being used by many developers. The cool thing about it is that you can change virtual paths by using the provider model. That means you can change all paths to exist in a database without your code knows about it.

  7. Avatar for Damon Stephenson
    Damon Stephenson June 13th, 2007

    Great article. I've missed .NET work for such a long time now. Can't wait to get back into it with my new job in 2 weeks.!

  8. Avatar for help.net
    help.net June 13th, 2007

    Phil Haack remind us that the framework contains a lot of utility classes like Syste.IO.Path or System

  9. Avatar for More Wally - Wallace B. McClur
    More Wally - Wallace B. McClur June 13th, 2007
  10. Avatar for JV
    JV June 13th, 2007

    Great article. Nobody knows the whole .NET framework by hearth, but there are some very intresting classes already mentioned which I always tend to forget =).
    Another nice one (2.0 only) is this:
    string a = "test";
    if(a == "") {
    }
    can be written into:
    if(string.IsNullOrEmpty(a))
    {
    }

  11. Avatar for Sergio
    Sergio June 13th, 2007

    Nice list Phil. Don't get me started with the List<T>'s Find____( .. ), RemoveAll(Predicate<T>) , and ForEach(Action<T>) ... They put a smile on my face every time I use them.

  12. Avatar for Matt Blodgett
    Matt Blodgett June 13th, 2007

    Dare I say...System.Text.RegularExpressions.Regex?

  13. Avatar for chrisb
    chrisb June 13th, 2007

    Can't wait for C# 3 extension methods.. then hopefully, even if developers don't know about some framework-provided class, their own code can at least be fairly standard and the extension method itself can be changed just once :)

  14. Avatar for Justin Pierce
    Justin Pierce June 13th, 2007

    Everything in the Enum and Array static classes should be on this list. I practically threw a party when I found out about Enum.Parse().

  15. Avatar for Danuz
    Danuz June 13th, 2007

    Namespace System.Net.NetworkInformation
    The class NetworkChange with interesting events : NetworkAddressChanged & NetworkAvailabilityChanged.
    Also the class NetworkInterface with the GetIsNetworkAvailable method.
    Working with network is easy, Life is easy ! ;)

  16. Avatar for Eric D. Burdo
    Eric D. Burdo June 13th, 2007

    @JV
    I was just reading this about IsNullOrEmpty. Might want to investigate a bit.
    http://msmvps.com/blogs/bil...

  17. Avatar for Aaron
    Aaron June 13th, 2007

    I never new Path.Combine existed until three months ago. Its just a problem of to much information.

  18. Avatar for Use little words...
    Use little words... June 13th, 2007

    Don't re-invent the wheel!

  19. Avatar for Jason Monroe
    Jason Monroe June 13th, 2007
  20. Avatar for Denny Ferrassoli
    Denny Ferrassoli June 13th, 2007

    Excellent article. Maybe a few people aren't aware of the System.Diagnostics.Stopwatch class. A hell of a lot better than subtracting time and it's fairly precise too.

  21. Avatar for Jayson Knight
    Jayson Knight June 13th, 2007

    I find myself using the static methods on the Char type quite a bit, specifically the "Is*" methods. Environment is a dandy, and it's amazing how many devs don't know about it (I like the SpecialFolders enumeration).

  22. Avatar for Jeff
    Jeff June 13th, 2007

    Nice post. Another useful one that you don't see too often that I use all the time is the static Format() method of the String class. String.Format("something {0}, {1}",var1,var2) is so much nicer than concatenation and makes things so much easier to read and work with.

  23. Avatar for Damien Guard
    Damien Guard June 13th, 2007

    If you find yourself writing a method to save time dealing with the system or environment then ask yourself "Why am I writing this?"
    Normally there is something to do what you want already. If it isn't exactly what you want then you've probably already taken a wrong turn somewhere.
    Luka's .NET Reflector tool is essential as you can search the entire framework by method or property name in a matter of seconds.
    [)amien

  24. Avatar for JV
    JV June 14th, 2007

    @Eric D. Burdo
    IsNullOrEmpty is still very common used in big frameworks and such applications. And lots of people are using it. A quick Google gives only 1 url (the one you posted) about the problem. You should ask yourself a second question about it: If the provided cause for this suspected bug is that big, why doesn't it happen more often then?

  25. Avatar for Doug Mayer
    Doug Mayer June 14th, 2007

    @Eric D. Burdo & JV,
    It looks like this may be fixed in Orcas Beta 1, according to the bug Bill reported. There is also a little insight in the workarounds (that it doesn't happen if the loop iterates < 4 times):
    http://connect.microsoft.co...

  26. Avatar for Richard P
    Richard P June 14th, 2007

    "You should ask yourself a second question about it: If the provided cause for this suspected bug is that big, why doesn't it happen more often then?"
    Because 99% of the time, people will not put String.IsNullOrEmpty *inside* the loop.
    The first line of the function would be
    if (String.IsNullOrEmpty(someArgument)) throw new ArgumentException("someArgument cannot be null or empty.");
    The bug exists, but it's rare because most developers just don't test well enough to expose a bug that only exists when run outside the IDE with optimizations on. Of those that do, very few situations call for putting the String.IsNullOrEmpty() test inside the loop.

  27. Avatar for Travis Illig
    Travis Illig June 14th, 2007

    XML reserved character encoding on a string:
    string System.Security.SecurityElement.Escape(string)
    System.CodeDom.Compiler.TempFileCollection is the bomb when you have to extract a bunch of temporary files and want to clean everything up automatically when you're done.
    And I'm still working on the goodness of "yield," which rocks but takes some getting used to: http://msdn2.microsoft.com/...
    Along the lines of HTML/URL encoding... is there any "ScriptEncode" sort of thing? Something that escapes quotes for you? I always end up with String.Replace for that.

  28. Avatar for DotNetKicks.com
    DotNetKicks.com June 14th, 2007

    You've been kicked (a good thing) - Trackback from DotNetKicks.com

  29. Avatar for DotNetKicks.com
    DotNetKicks.com June 14th, 2007

    You've been kicked (a good thing) - Trackback from DotNetKicks.com

  30. Avatar for Golf Scrambles
    Golf Scrambles June 14th, 2007

    Speaking of .NET - just noticed that Orcas got renamed to Visual Studio 2008... When did this happen?

  31. Avatar for Christopher Steen
    Christopher Steen June 14th, 2007

    TechEd Session: Deploying Smart Client Architectures [Via: brian@softinsight.com ] TechEd Session: WPF/Windows...

  32. Avatar for Brennan Stehling
    Brennan Stehling June 14th, 2007

    One feature in C# that I did not know about until 1 year into working in .NET was the "as" operator. Normally to cast an object from a collection safely I would do this...
    if (obj is SomeClass) {
    SomeClass sc = (SomeClass) obj;
    }
    A more efficient way that I like better is...
    SomeClass sc = obj as SomeClass;
    if (sc != null) {
    // use sc
    }
    The second one is just a smidge more efficient. I like to use this in ASP.NET code-behind classes with the FindControl method.
    Label lbl = FindControl("Label1") as Label;
    if (lbl != null) {
    lbl.Text = "Set the text property";
    }
    I think it keeps the code fairly compact but I often see many developers just blindly cast controls with the FindControl method and it normally works but it is easy to break.
    This is the a great post and group of comments. I hope you do a summary in a few days.

  33. Avatar for Haacked
    Haacked June 14th, 2007

    @Brennan - good idea!
    I should add the Null Coalescing Operator. A lot of people forget about this one.

  34. Avatar for Simone Chiaretta
    Simone Chiaretta June 14th, 2007

    I love the String.IsNullOrEmpty(string)

  35. Avatar for Jannik Anker
    Jannik Anker June 14th, 2007

    The Most Useful .NET Utility Classes Developers Tend To Reinvent Rather Than Reuse

  36. Avatar for Wiennat's Blog
    Wiennat's Blog June 14th, 2007

    Useful .NET Utility Classes

  37. Avatar for lb
    lb June 14th, 2007

    As soon as I saw the title of this article I thought "Path" -- and in particular Path.Combine.
    Html/Url en/de code are great ones too.
    What's missing? tough one...
    StringBuilder.AppendFormat ... maybe? (People either forget to use stringbuilders at all, or use StringBuilder.Append(String.Format(...
    Anyway Phil -- Hope little thugy is going well ;-)

  38. Avatar for jrummell
    jrummell June 14th, 2007

    This is good stuff. This is the first I've heard of VirtualPathUtility, thanks for sharing.

  39. Avatar for Creative Minds
    Creative Minds June 14th, 2007

    The Most Useful .NET Utility Classes Developers Tend To Reinvent Rather Than Reuse

  40. Avatar for David Gladfelter
    David Gladfelter June 14th, 2007

    >>Dare I >>say...System.Text.RegularExpressions.Regex?
    Matt, I totally agree, however this is programmer laziness rather than ignorance. I try to avoid sounding dogmatic, but I believe that regular expressions is an entry-level skill for programmers. It's one of the most powerful and widely-applicable domain-specific language out there.

  41. Avatar for David Gladfelter
    David Gladfelter June 14th, 2007

    Matt Blodget said:


    >>Dare I say...System.Text.RegularExpressions.Regex?


    Matt, I totally agree, however this is programmer laziness rather than ignorance. I try to avoid sounding dogmatic, but I believe that knowledge of regular expressions is an entry-level skill for programmers. It's one of the most powerful and widely-applicable domain-specific language out there.
    I find System.Bitconverter to be underused in an application domain in which I do a lot of work, I/O and communications. Unmanaged interop really benefits from this along with System.Runtime.InteropServices.Marshal. Along those lines, System.Text.Encoding is also very useful.

  42. Avatar for Christopher Bennage
    Christopher Bennage June 15th, 2007

    Phil Haack made an excellent post that I just have to propagate. It's his list of overlooked utility

  43. Avatar for Kyralessa
    Kyralessa June 16th, 2007

    I don't agree as far as Path.Combine. Have a look at the documentation for it:
    http://msdn2.microsoft.com/...
    If the second argument starts with a root (i.e. backslash), Path.Combine returns just the second argument and ignores the first completely. Personally, that's not the behavior I'd expect; I'd expect it to combine the two paths in all cases, making sure there aren't too many or too few backslashes.

  44. Avatar for StevenHarman.net
    StevenHarman.net June 16th, 2007

    URL and HTML Encoding on the Client? JavaScript to the Rescue!

  45. Avatar for Steven Harman
    Steven Harman June 16th, 2007

    @Kyralessa: Seems to me this might be a case of Path.Combine breaking the Principle of Least Surprise... of course, MS probably calls that a feature. :)

  46. Avatar for wwfDev
    wwfDev June 17th, 2007

    @Kyralessa: I totally agree - Path.Combine has way too much surprises up it's sleeve to be solid and clear about it's output. My advice - write your own library for this, document it well, throw in some samples (who knows, you may use it again...) and use it!

  47. Avatar for Dityo Nurasto
    Dityo Nurasto June 17th, 2007

    Nice article. I replace my application code to use System.Web.VirtualPathUtility and I use the wheel now ;) . Thanks a lot for sharing this.

  48. Avatar for Darren
    Darren June 17th, 2007

    I am new to .net programming. Any suggestions about how to learn the framework? Any shortcuts?

  49. Avatar for Haacked
    Haacked June 18th, 2007

    @Darren - I recommend reading CLR via C#. If you're doing ASP.NET programming, check out Fritz Onion's book, Essential ASP.NET vol 1 and 2.

  50. Avatar for Vlad Iliescu
    Vlad Iliescu June 18th, 2007

    Unfortunately, VirtualPathUtility doesn't handle query string parameters, making it useless for us. Back to using a private Control and calling its ResolveUrl method.

  51. Avatar for Sameer
    Sameer June 18th, 2007

    @Darren - After you have some know how on .NET, how about joining a project like subtext that will allow you to see some real source code and work with it? ;)

  52. Avatar for Josh Stodola
    Josh Stodola June 21st, 2007

    Is VirtualPathUtility.ToAbsolutePath the same as ResolveUrl?
    I have always just used ResolveUrl, should I change? Why?

  53. Avatar for DotNetKicks.com
    DotNetKicks.com June 25th, 2007

    You've been kicked (a good thing) - Trackback from DotNetKicks.com

  54. Avatar for ChrisMo
    ChrisMo June 26th, 2007

    Can't tell you how many times I've seen people format stats using subString to control the number of decimal places instead of the ToString(format,IFormatProvider) overload:
    i.e.:
    private NumberFormatInfo formatProvider;
    formatProvider.NumberDecimalDigits = 2;
    lblAvg2Decs.Text = avg.ToString("N", formatProvider);
    formatProvider.NumberDecimalDigits = 1;
    lblAvg1Decs.Text = avg.ToString("N", formatProvider);

  55. Avatar for ChrisMo
    ChrisMo June 26th, 2007

    Woops, I meant :
    Double d = 3.14 / 3;
    NumberFormatInfo formatProvider = new CultureInfo("en-US", false).NumberFormat ;
    formatProvider.NumberDecimalDigits = 2;
    Console.WriteLine( d.ToString( "N", formatProvider ) );
    formatProvider.NumberDecimalDigits = 3;
    Console.WriteLine( d.ToString( "N", formatProvider ) );

  56. Avatar for Robbie
    Robbie June 26th, 2007

    HttpUtility.ParseQueryString is one I recently wished I knew about earlier...

  57. Avatar for Chris Love's Official Blog - P
    Chris Love's Official Blog - P July 1st, 2007

    Where oh where have my links of the week gone? Well I have been overwhelmed with work the past couple

  58. Avatar for CrashCodes
    CrashCodes July 2nd, 2007

    For the trailing path delimiter code, steal the idea from the Delphi libraries and create a function (something like):

    void IncludeTrailingPathDelimiter(ref String path) {
    if (!path.EndsWith(Path.DirectorySeparatorChar.ToString()))
    path += Path.DirectorySeparatorChar;
    }

    that concats the path delimiter if it is not the last character.
    To avoid needless calls, it might also be a good idea to put whether or not the path delimiter is returned as part of the GetFullPath() function summary. I heart intellisense features.
    Enjoy

  59. Avatar for Navdeep Bhardwaj
    Navdeep Bhardwaj November 6th, 2007

    I like TryParse method introduced in .NET 2. Using it you can cast variable type and perform anything if the cast fails, without raising any type case error or relying on exceptions to handle situation.

  60. Avatar for G.
    G. December 4th, 2008

    Great post. As usual.
    I'd like to ask a question though: What is the difference b/w using 'Environment.NewLine' and 'vbNewLine' (other than obvious language dependency and literal vs property)?

  61. Avatar for pandu
    pandu July 6th, 2010

    what is .net?why it is
    usin

  62. Avatar for pandu
    pandu July 6th, 2010

    what is .net?why it is using?where it is using?what are the addvantage and disadvantage?

  63. Avatar for Chris
    Chris August 7th, 2010

    Okay I tend to agree BUT.
    What do I do in this case?
    Situation: I have a css file for which I know the path, I need to find the full path for the urls in this css file. A url could be:
    ../images/somefile.jpg
    ../../../somefile.jpg
    /Images/somefile.jpg
    Do you know how to handle this with the built in utilities?
    Thanks.

  64. Avatar for GDS
    GDS June 22nd, 2011

    New feature in 4.0 which checks Null, empty as well as White space which can be used if blank spaces also needs to be validated by String.IsNullOrWhiteSpace(string) inplace of String.IsNullOrEmpty(string).