Tuesday, 13 November 2012

Long File Paths in .NET

This may be something that most people are unaware of but Windows has a nice legacy feature which limits path names to 260 characters - try to create a hierarchy that exceeds this and you will get a nice error message. However with enough persistence you can get round this limitation and create paths greater than the limit. 

The problem with this is when you come to read the paths through .NET code everything falls over. This was the problem I was faced with recently at work whilst trying to move some files from one place to another.

I tried a few different things to get around this - creating a network share to make the path smaller, using the folder short names but nothing worked. I then discovered that Windows does have a mechanism for dealing with this by using this path format  "\\?\". This tells it to use long paths which can then use a maximun of 32,767 characters.

Of course nothing is that easy and the .NET methods simply do not handle this situation so the only real solution is to call into the Windows API directly. I started to have a look round for a library that already did this and voila I came across AlphaFS an open source project which does exactly that.

The library recreates all the methods you might need for interacting with directories/files etc but with the twist that you can now pass in the long path format and it will work correctly!