Monday, October 7, 2013

Tackling the PathTooLongException

I received a System.IO.PathTooLongException the other day while deleting some files using System.IO.File.Delete. It seems that .net cannot handle long file names and I had to revert to plain old win32 api to do the job using the following declaration:

using System;
using System.Runtime.InteropServices;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteFile(string lpFileName);
// This code snippet is provided under the Microsoft Permissive License.
public static void Delete(string fileName) {
// call it with a file name prefixed by \\?\:
string formattedName = @"\\?\" + fileName;
DeleteFile(formattedName);
}

I have also spotted Delimon.Win32.I​O Library (V4.0) which I would have used if it was available as a Nuget package. This lib provides a lot of System.IO classes using the win32 api instead, handy if you are dealing with long filenames.

No comments: