如何克服 PathTooLongException?

发布于 2024-11-09 20:25:34 字数 358 浏览 0 评论 0原文

因此,我正在编写一个程序,该程序将扫描计算机上的重复文件,因为我见过的程序非常慢,并且/或占用内存,但是当我尝试时,我遇到了 PathTooLongException 。到整个驱动器。阅读 C# 代码中的 PathTooLongException 后,我对以下两个问题感到好奇。

  1. 如果每次更改级别时都切换当前目录,会影响我的性能吗?

  2. 有没有更好的方法来获取所有文件的目录结构(也许通过调用诸如tree.exe之类的东西然后解析它)?

So I am writing a program that will scan for duplicate files on a computer as the programs that I've seen are really slow, and/or memory hogs, but I was running into a PathTooLongException when I tried to the whole drive. After reading PathTooLongException in C# code I became curious about the following two questions.

  1. Would it hurt my performance if I were to switch my current directory every time I changed levels?

  2. Is there a better way to get the directory structure of all the files (perhaps by calling something like tree.exe and then parsing that)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

刘备忘录 2024-11-16 20:25:34

或者自己做,

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern IntPtr FindFirstFile(string lpFileName, out
                                WIN32_FIND_DATA lpFindFileData);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern bool FindNextFile(IntPtr hFindFile, out
                                WIN32_FIND_DATA lpFindFileData);

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FindClose(IntPtr hFindFile);

// Assume dirName passed in is already prefixed with \\?\
public static IEnumerable<string> EnumerateEntries(string directory)
{ 
    WIN32_FIND_DATA findData;
    IntPtr findHandle = FindFirstFile(dirName + @"\*", out findData);

    try
    {
        if (findHandle != INVALID_HANDLE_VALUE)
        {
            bool found;
            do
            {
                string currentFileName = findData.cFileName;

                // if this is a directory, find its contents
                if (((int)findData.dwFileAttributes &
                                FILE_ATTRIBUTE_DIRECTORY) != 0)
                {
                    if (currentFileName != "." && currentFileName != "..")
                    {
                        foreach(var child in FindFilesAndDirs(
                                Path.Combine(dirName, currentFileName))
                        {
                            yield return child;
                        }
                    }
                }

                yield return Path.Combine(dirName, currentFileName);

                // find next
                found = FindNextFile(findHandle, out findData);
            }
            while (found);
        }

    }
    finally
    {
        // close the find handle
        FindClose(findHandle);
    }
}

我还没有验证这个代码,显然并不是所有的类型都被定义,但它应该为我们指明正确的方向。

or do it yourself,

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern IntPtr FindFirstFile(string lpFileName, out
                                WIN32_FIND_DATA lpFindFileData);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern bool FindNextFile(IntPtr hFindFile, out
                                WIN32_FIND_DATA lpFindFileData);

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FindClose(IntPtr hFindFile);

// Assume dirName passed in is already prefixed with \\?\
public static IEnumerable<string> EnumerateEntries(string directory)
{ 
    WIN32_FIND_DATA findData;
    IntPtr findHandle = FindFirstFile(dirName + @"\*", out findData);

    try
    {
        if (findHandle != INVALID_HANDLE_VALUE)
        {
            bool found;
            do
            {
                string currentFileName = findData.cFileName;

                // if this is a directory, find its contents
                if (((int)findData.dwFileAttributes &
                                FILE_ATTRIBUTE_DIRECTORY) != 0)
                {
                    if (currentFileName != "." && currentFileName != "..")
                    {
                        foreach(var child in FindFilesAndDirs(
                                Path.Combine(dirName, currentFileName))
                        {
                            yield return child;
                        }
                    }
                }

                yield return Path.Combine(dirName, currentFileName);

                // find next
                found = FindNextFile(findHandle, out findData);
            }
            while (found);
        }

    }
    finally
    {
        // close the find handle
        FindClose(findHandle);
    }
}

I haven't verified this code and obviously not all the types are defined but it should point us in the right direction.

紫罗兰の梦幻 2024-11-16 20:25:34

纯 C#,需要优化,但无需使用外部库或 p/invoking 即可为人们提供领先优势。

public static class DirectoryEx
{
    static char driveLetter;
    static string longPath;
    static List<string> directories;

    static DirectoryEx()
    {
        longPath = String.Empty;
    }

    private static char GetAvailableDrive()
    {
        var all = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray().Reverse();
        var occupied = DriveInfo.GetDrives()
            .OrderByDescending(d => d.Name)
            .Select(d => (char)d.Name.ToUpper().First());

        var free = all.Except(occupied).First();

        return free;
    }

    public static List<string> GetDirectories(string path)
    {
        directories = new List<string>();

        // recursive call
        FindDirectories(path);

        return directories;
    }

    static void FindDirectories(string path)
    {
        try
        {
            foreach (var directory in Directory.GetDirectories(path))
            {
                var di = new DirectoryInfo(directory);

                if(!String.IsNullOrEmpty(longPath))
                    directories.Add(di.FullName.Replace(driveLetter + ":\\", longPath + "\\"));
                else
                    directories.Add(di.FullName);

                FindDirectories(di.FullName);
            }
        }
        catch (UnauthorizedAccessException uaex) { Debug.WriteLine(uaex.Message); }
        catch (PathTooLongException ptlex)
        {
            Debug.WriteLine(ptlex.Message);

            longPath = path;

            Task t = new Task(new Action(() =>
            {
                CreateVirtualDrive(longPath);
                FindDirectories(driveLetter + ":\\");
                DeleteVirtualDrive();

                longPath = String.Empty;
            }));

            if (!String.IsNullOrEmpty(longPath))
                t.RunSynchronously();
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message); 
        }
    }

    static void CreateVirtualDrive(string path)
    {
        driveLetter = GetAvailableDrive();

        Process.Start(new ProcessStartInfo() {
            FileName = "cmd.exe",
            WindowStyle = ProcessWindowStyle.Hidden,
            Arguments = String.Format("/c subst {0}: {1}", driveLetter.ToString(), path)
        });

        while (!DriveInfo.GetDrives().Select(d => d.Name.ToUpper().First()).Contains(driveLetter))
        {
            System.Threading.Thread.Sleep(1);
        }
    }

    static void DeleteVirtualDrive()
    {
        Process.Start(new ProcessStartInfo()
        {
            FileName = "cmd.exe",
            WindowStyle = ProcessWindowStyle.Hidden,
            Arguments = String.Format("/c subst {0}: /D", driveLetter.ToString())
        });

        while (DriveInfo.GetDrives().Select(d => d.Name.ToUpper().First()).Contains(driveLetter))
        {
            System.Threading.Thread.Sleep(1);
        }
    }
}

Pure C#, needs optimization but will give people a headstart without using an external library or p/invoking..

public static class DirectoryEx
{
    static char driveLetter;
    static string longPath;
    static List<string> directories;

    static DirectoryEx()
    {
        longPath = String.Empty;
    }

    private static char GetAvailableDrive()
    {
        var all = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray().Reverse();
        var occupied = DriveInfo.GetDrives()
            .OrderByDescending(d => d.Name)
            .Select(d => (char)d.Name.ToUpper().First());

        var free = all.Except(occupied).First();

        return free;
    }

    public static List<string> GetDirectories(string path)
    {
        directories = new List<string>();

        // recursive call
        FindDirectories(path);

        return directories;
    }

    static void FindDirectories(string path)
    {
        try
        {
            foreach (var directory in Directory.GetDirectories(path))
            {
                var di = new DirectoryInfo(directory);

                if(!String.IsNullOrEmpty(longPath))
                    directories.Add(di.FullName.Replace(driveLetter + ":\\", longPath + "\\"));
                else
                    directories.Add(di.FullName);

                FindDirectories(di.FullName);
            }
        }
        catch (UnauthorizedAccessException uaex) { Debug.WriteLine(uaex.Message); }
        catch (PathTooLongException ptlex)
        {
            Debug.WriteLine(ptlex.Message);

            longPath = path;

            Task t = new Task(new Action(() =>
            {
                CreateVirtualDrive(longPath);
                FindDirectories(driveLetter + ":\\");
                DeleteVirtualDrive();

                longPath = String.Empty;
            }));

            if (!String.IsNullOrEmpty(longPath))
                t.RunSynchronously();
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message); 
        }
    }

    static void CreateVirtualDrive(string path)
    {
        driveLetter = GetAvailableDrive();

        Process.Start(new ProcessStartInfo() {
            FileName = "cmd.exe",
            WindowStyle = ProcessWindowStyle.Hidden,
            Arguments = String.Format("/c subst {0}: {1}", driveLetter.ToString(), path)
        });

        while (!DriveInfo.GetDrives().Select(d => d.Name.ToUpper().First()).Contains(driveLetter))
        {
            System.Threading.Thread.Sleep(1);
        }
    }

    static void DeleteVirtualDrive()
    {
        Process.Start(new ProcessStartInfo()
        {
            FileName = "cmd.exe",
            WindowStyle = ProcessWindowStyle.Hidden,
            Arguments = String.Format("/c subst {0}: /D", driveLetter.ToString())
        });

        while (DriveInfo.GetDrives().Select(d => d.Name.ToUpper().First()).Contains(driveLetter))
        {
            System.Threading.Thread.Sleep(1);
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文