Wednesday 24 June 2015

Dealing with PathTooLongException while scanning files with long paths in C#

Suppose you have a list of object of class ‘FileInfo’. This class provide properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
List<FileInfo> AllFilesInfo;
Let say you have a DataTable 'dt' with columns ‘Name’ and ‘Path’. For all the files in AllFilesInfo object, you want to fill in the name and directory name in dataTable.
foreach (FileInfo fileInfo in AllFilesInfo)
{
       DataRow dr = dt.NewRow();
       dr[0] = fileInfo.Name;
       dr[1] = fileInfo.DirectoryName;
}
The above code works well if you don’t have any file with long path. But as soon as, your code finds any such file, you will encounter the below exception:
PathTooLongException  was caught: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
When you debug and add a watch for fileInfo object, you will find both Directory and DirectoryName are throwing this exception. Now if you expand the ‘Non-public members’ and then the ‘base’ object of ‘fileInfo’, you will see a property named ‘FullPath’ giving the fullpath, which is what you need.


‘FullPath’ is a protected property of class ‘FileSystemInfo’, which is a base class for both ‘FileInfo’ and ‘DirectoryInfo’. You can access the path as follows:
DataRow dr = dt.NewRow();
dr[0] = fileInfo.Name;
try
{
    dr[1] = fileInfo.DirectoryName;
}
catch (PathTooLongException ex)
{
    FieldInfo fld = typeof(FileSystemInfo).GetField(
                                                    "FullPath",
                                                     BindingFlags.Instance |
                                                     BindingFlags.NonPublic);
    string fullPath = fld.GetValue(fileInfo).ToString();
    fullPath = fullPath.Remove(fullPath.IndexOf(fileInfo.Name)); // Removing file name from the fullpath
    dr[1] = fullPath;
}
By using the above code, you can access the fullPath of files with long names.

No comments:

Post a Comment