Friday, July 30, 2010

Retrieving a File or Directory from a Path that is Too Long to Read - C#

Microsoft has a limitation of 260 characters for a path or file name. Usually Windows is smart enough and wont allow you to create a file or folder if the path will be too long, but sometimes, some way or another, files/folders get trapped and you can't access them because the name is too long. This can be a huge inconvenience and can cause your program to crash.

The following method overwrites the Windows API and allows you to move a folder or directory if its path is over 260 characters:
Note: Replace "H:\Calvin\kernel32.dll" with the path to kernel32.dll (can be found in your system32 folder)
Note2: You can call Move on a directory or file
[DllImport(@"H:\Calvin\kernel32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool MoveFile(string lpExistingFileName, string lpNewFileName);

public static void Move(string fileName, string toPath) 
{
    string formattedName = @"\\?\" + fileName;
    MoveFile(formattedName, toPath);
            
}

If you have the problem where you don't the exact path you want to retrieve because you can't access it in the first place, ABTO created a nice little DLL that helps you with paths that are too long. The trial version has enough functionality to work. Download it HERE.

If you want to do other functions besides move a file, check out the File Management Functions documentation and alter the above code.

References:
Kim Hamilton

0 comments:

Post a Comment