C# How can I solve limitations when using DirectoryInfo?

Phu Minh Pham picture Phu Minh Pham · Mar 6, 2012 · Viewed 12.7k times · Source

When I recursive through some folders and files, I encounter this error:

The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directoryname must be less than 248 characters.

Here's my function

private void ProcessDirectory(DirectoryInfo di)
{
    try
    {
        DirectoryInfo[] diArr = di.GetDirectories();

        foreach (DirectoryInfo directoryInfo in diArr)
        {
            if (StopCheck)
                    return;
            ProcessDirectory(directoryInfo);
        }
        ProcessFile(di);
    }
    catch (Exception e)
    {
        listBoxError.Items.Add(e.Message);
    }

    TextBoxCurrentFolder.Text = di.ToString();
}

I cannot make the directory names shorter, because I'm not allowed too so... How can I solve this problem?

Added: Here's the other function:

private void ProcessFile(DirectoryInfo di)
{
    try
    {
        FileInfo[] fileInfo = di.GetFiles();

        if (fileInfo.LongLength != 0)
        {
            foreach (FileInfo info in fileInfo)
            {
                Size += info.Length;
                CountFile++;
            }
        }
    }
    catch (Exception e)
    {
        listBoxError.Items.Add(e.Message);
    }
}

EDIT Found this where he used Zeta Long Paths: How can I use FileInfo class, avoiding PathTooLongException?

Have implemented it and now i'm going to let the program run over the night to see if it works.

EDIT Used the ZetaLongPath yesterday and it worked great! It even went through folders that needed permission access.

EDIT Instead of zetalongPath, I've used Delimon.Win32.IO.dll which i think is much better. It has the same interfaces as Win32.

Answer

TripleAntigen picture TripleAntigen · Feb 16, 2013

Here's more info about the Delimon library referred to earlier. Its a .NET Framework 4 based library on Microsoft TechNet for overcoming the long filenames problem:

Delimon.Win32.I​O Library (V4.0).

It has its own versions of key methods from System.IO. For example, you would replace:

System.IO.Directory.GetFiles 

with

Delimon.Win32.IO.Directory.GetFiles

which will let you handle long files and folders.

From the website:

Delimon.Win32.IO replaces basic file functions of System.IO and supports File & Folder names up to up to 32,767 Characters.

This Library is written on .NET Framework 4.0 and can be used either on x86 & x64 systems. The File & Folder limitations of the standard System.IO namespace can work with files that have 260 characters in a filename and 240 characters in a folder name (MAX_PATH is usually configured as 260 characters). Typically you run into the System.IO.PathTooLongException Error with the Standard .NET Library.