Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to check if length exceeds MAX_PATH or catch PathTooLongException?

I'm writing a C# program that uses System.IO methods to work with files and directories. Some of these methods include Directory.GetDirectories, Directory.GetFiles, and Path.GetDirectoryName which can all throw the PathTooLongException exception if the path is too long. My first question is does the Microsoft .NET Framework enforce the maximum length of a path, the same way that a call to a Windows API in C++ does? Does a path (in a string) in C# that exceeds MAX_PATH cause PathTooLongException to be thrown?

Should I use this?

string getFolderName(string path) 
{
    if (string.IsNullOrWhiteSpace(path))
        return string.Empty;

    if (path.Length > 260)
    {
        System.Diagnostics.Debug.WriteLine("Path is too long.");
        return string.Empty;
    }

    string folderName = System.IO.Path.GetDirectoryName(path);

    return folderName;
}

Or this?

string getFolderName(string path) 
{
    if (string.IsNullOrWhiteSpace(path))
        return string.Empty;

    string folderName = string.Empty;

    try {
        folderName = System.IO.Path.GetDirectoryName(path);
    }
    catch (System.IO.PathTooLongException)
    {
        System.Diagnostics.Debug.WriteLine("Path is too long.");
    }

    return folderName;
}
like image 271
ub3rst4r Avatar asked Sep 16 '25 14:09

ub3rst4r


1 Answers

Better is a judgment call.

Catching an exception is a much slower operation than testing for the condition and avoiding the exception entirely. However, unless you are going to encounter a large number of exceptions, the performance difference is simply not important.

It is hard too imagine a case where you would get large numbers of path too long errors, unless you are trying to do something where are copying or moving tree into a directory node that is already deep. In which case, you are probably better off to test everthing up front so you don't create a large slow operation that will fail in the middle.

However, a hard-coded 260 is a bad idea anyway as this previous answer shows.

There is no built-in windows function that gives the real answer for a given system, but you could simply determine the answer by trial and error (maybe a binary search) on the user system before starting your operations.

However, if you read the article I referenced, you will see that you can easily create longer paths in a program than will work well in windows. Windows explorer has problems once you reach 255 characters, so long story short, I would recommend a limit of 255 at most if you have any choice in the matter.

like image 90
Gary Walker Avatar answered Sep 18 '25 03:09

Gary Walker