07 Sep 2009

When it comes to build full path files strings in C# or Java, I very often see methods being reinvented again and again.

However, both framework offer utility classes to do just that for you. An it has been developed by some of the most skilled developers on the planet. How can you beat that? So stop rolling out your own path building functions!

.NET Version (in C#)

I’m always astonished that so many developers don’t know the System.IO.Path utility static class of the .NET Framework.

As an example, see this code:

String file1 = Path.Combine(@"C:\tmp\test
, "test.txt"); String file2 = Path.Combine(@"C:\tmp\test", "test.txt"); //file1 == file2 //"C:\tmp\test\test.txt" Console.WriteLine("File: {0}", file1);

Doesn’t matter if you forgot the “\” at the end of the directory string, it will be added. If it’s already there, it’s also fine! If you don’t know that stuff yet, have a look at the others methods available.

Now, onto Java.

Java Version

Java has the File class to do that. It’s very easy to use, but it doesn’t work the same way. You have to instantiate a new File object every time, instead of calling a static method like in .NET.

File file1 = new File("C:\tmp\test", "test.txt");
File file2 = new File("C:\tmp\test\", "test.txt");

Now, this object is an abstract representation of the “C:\tmp\test\test.txt” file, so if you call toString() on it, you get that path as a string.

Side Notes

Two interesting things I noticed while writing this.

First, a difference between .NET and Java path creators. The .NET Path.Combine will return only the second string if it starts with the “\” character, while the Java File class will ignore it. the .NET class probably assumes that it’s a relative path, while the Java class ignores it.

Second, if you try to create an instance of the .NET Path class, Visual Studio will give you the following error message: “Cannot create an instance of the abstract class or interface 'System.IO.Path'”. Once you tried to build, if fails and the error message changes to “Cannot create an instance of the static class 'System.IO.Path'”. It’s clearly related to Visual Studio, but it’s the first time I notice that behavior (the first error message was quite suspicious with the “abstract class or interface” thingy). Anyway, Visual Studio warns you that it cannot be done, which is the important thing, then it refines it’s error message based on the output of the compiler.

blog comments powered by Disqus