Tuesday, January 12, 2010

A common mistake with FileInfo

This is an interesting one because it is usually not caught by mechanical tools. Consider the following three "equivalent" statements.

  • var x0 = new FileInfo(somefolder + filename);
  • var x1 = new FileInfo(String.Format("{0}{1}",somefolder , filename));
  • var x2 = new FileInfo(Path.Combine(somefolder, filename));
x0 will usually be caught by mechanical code and then recommend variation x1. Both x0 and x1 are problematic because they are very sensitive to the presence or omission of an ending "\" in somefolder.

The correct way is to use Path.Combine which both accommodate the "\" issue but does additional checking of the content.

No comments:

Post a Comment