如何避免System.IO.PathTooLongException?

时间:2009-02-09 21:38:39

标签: c# .net

我们经常遇到这个问题...

示例:

如果我有一个文件,我想将它复制到另一个目录或UNC共享,如果路径的长度超过248(如果我没有记错),那么它会抛出PathTooLongException。这个问题有解决办法吗?

PS:是否有任何注册表设置将此路径设置为更长的字符集?

10 个答案:

答案 0 :(得分:20)

如Jeremy Kuhne的blog所述,.NET Framework 4.6.2尽可能消除MAX_PATH限制,而不会破坏向后兼容性。

答案 1 :(得分:11)

试试这个: Delimon.Win32.I O Library(V4.0) 这个Libarary是在.NET Framework 4.0上编写的

Delimon.Win32.IO取代了System.IO的基本文件功能,并支持File&文件夹名称最多为 32,767 字符。

https://gallery.technet.microsoft.com/DelimonWin32IO-Library-V40-7ff6b16c

此库是专门为克服.NET Framework的限制而使用long Path&文件名。使用此库,您可以以编程方式浏览,访问,写入,删除等System.IO namespace.Library无法访问的文件和文件夹。

<强>用法

  1. 首先在项目中添加对Delimon.Win32.IO.dll的引用 (浏览到Delimon.Win32.IO.dll文件)

  2. 在您的代码文件中添加“使用Delimon.Win32.IO”

  3. 使用普通文件&amp;目录对象就像您正在使用一样 System.IO

答案 2 :(得分:8)

BCL团队已对此进行了深入讨论,请参阅blog entries

本质上,无法在.Net代码中执行此操作并坚持使用BCL。太多的函数依赖于能够规范化路径名(这会立即触发使用期望遵循MAX_PATH的函数)。

你可以包装所有支持“\\?\”语法的win32函数,使用这些函数你可以实现一套长路径感知功能,但这很麻烦。

由于大量工具(包括explorer [1])无法处理长路径名称,因此除非您对与生成的文件系统进行所有交互感到高兴,否则不宜沿着这条路径走下去你的图书馆(或者像robocopy一样用来处理它的有限数量的工具)

为了满足您的具体需求,我会调查直接使用robocopy是否足以执行此任务。

[1] Vista有一些方法可以通过引擎盖下的一些花哨的重命名来缓解这个问题,但这最多是脆弱的。

答案 3 :(得分:4)

我在这一个上看过的只有一个解决方法......这可能会有所帮助

http://www.codeproject.com/KB/files/LongFileNames.aspx

答案 4 :(得分:2)

问题在于Windows API的ANSI版本。需要仔细测试的一个解决方案是强制使用Unicode版本的Windows API。这可以通过将“\\?\”添加到要查询的路径来完成。

包括解决方法在内的精彩信息可以在Microsoft的基类库(BCL)团队的以下博客文章中找到,该博客标题为“.NET中的长路径”:

答案 5 :(得分:2)

答案 6 :(得分:1)

此库可能会有所帮助: Zeta Long Paths

答案 7 :(得分:1)

我的云端硬盘映射解决方案运行良好且稳定 使用下面列出的“NetWorkDrive.cs”和“NetWorkUNCPath.cs”。

测试示例:

if (srcFileName.Length > 260)
{
   string directoryName = srcFileName.Substring(0, srcFileName.LastIndexOf('\\'));

   var uncName = GetUNCPath(srcFileName.Substring(0, 2)) + directoryName.Substring(2);

   using (NetWorkDrive nDrive = new NetWorkDrive(uncName))
   {
     drvFileName = nDrive.FullDriveLetter + Path.GetFileName(sourceFileName)
     File.Copy(drvFileName, destinationFileName, true);
   }
}
else
{
   File.Copy(srcFileName, destinationFileName, true);
}

NetWorkDrive.cs 源代码:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace SeekCopySupportTool.Business
{

public class NetWorkDrive : IDisposable
{
    #region private fields
    private string m_DriveLetter = string.Empty;
    private string m_FullDriveLetter = string.Empty;
    private bool m_Disposed = false;
    //this list specifies the drive-letters, whitch will be used to map networkfolders
    private string[] possibleDriveLetters = new string[] 
    { 
        "G:\\", 
        "H:\\", 
        "I:\\", 
        "J:\\", 
        "K:\\", 
        "L:\\", 
        "M:\\", 
        "N:\\", 
        "O:\\", 
        "P:\\", 
        "Q:\\", 
        "R:\\", 
        "S:\\", 
        "T:\\", 
        "U:\\", 
        "V:\\", 
        "W:\\", 
        "X:\\", 
        "Y:\\", 
        "Z:\\" 
    };
    #endregion

    #region public properties
    public string DriveLetter
    {
        get { return m_DriveLetter; }
        set { m_DriveLetter = value; }
    }
    public string FullDriveLetter
    {
        get { return m_FullDriveLetter; }
        set { m_FullDriveLetter = value; }
    }
    #endregion

    #region .ctor
    public NetWorkDrive(string folderPath)
    {
        m_FullDriveLetter = MapFolderAsNetworkDrive(folderPath);
        if (string.IsNullOrEmpty(m_FullDriveLetter))
        {
            throw new Exception("no free valid drive-letter found");
        }
        m_DriveLetter = m_FullDriveLetter.Substring(0,2);
    }
    #endregion

    #region private methods
    /// maps a given folder to a free drive-letter (f:\)
    /// <param name="folderPath">the folder to map</param>
    /// <returns>the drive letter in this format: "(letter):\" -> "f:\"</returns>
    /// <exception cref="Win32Exception">if the connect returns an error</exception>
    private string MapFolderAsNetworkDrive(string folderPath)
    {
        string result = GetFreeDriveLetter();
        NETRESOURCE myNetResource = new NETRESOURCE();
        myNetResource.dwScope = ResourceScope.RESOURCE_GLOBALNET;
        myNetResource.dwType = ResourceType.RESOURCETYPE_ANY;
        myNetResource.dwDisplayType = ResourceDisplayType.RESOURCEDISPLAYTYPE_SERVER;
        myNetResource.dwUsage = ResourceUsage.RESOURCEUSAGE_CONNECTABLE;
        myNetResource.lpLocalName = result.Substring(0,2);
        myNetResource.lpRemoteName = folderPath;
        myNetResource.lpProvider = null;
        int errorcode = WNetAddConnection2(myNetResource, null, null, 0);
        if(errorcode != 0)
        {
            throw new Win32Exception(errorcode);
        }
        return result;
    }
    private void DisconnectNetworkDrive()
    {
        int CONNECT_UPDATE_PROFILE = 0x1;
        int errorcode = WNetCancelConnection2(m_DriveLetter, CONNECT_UPDATE_PROFILE, true);
        if (errorcode != 0)
        {
            throw new Win32Exception(errorcode);
        }
    }

    private string GetFreeDriveLetter()
    {
        //first get the existing driveletters
        const int size = 512;
        char[] buffer = new char[size];
        uint code = GetLogicalDriveStrings(size, buffer);
        if (code == 0)
        {                
            return "";
        }
        List<string> list = new List<string>();
        int start = 0;
        for (int i = 0; i < code; ++i)
        {
            if (buffer[i] == 0)
            {
                string s = new string(buffer, start, i - start);
                list.Add(s);
                start = i + 1;
            }
        }            
        foreach (string s in possibleDriveLetters)
        {                
            if (!list.Contains(s))
            {
                return s;
            }
        }
        return null;
    }        
    #endregion

    #region dll imports
    /// <summary>
    /// to connect to a networksource
    /// </summary>
    /// <param name="netResource"></param>
    /// <param name="password">null the function uses the current default password associated with the user specified by the username parameter ("" the function does not use a password)</param>
    /// <param name="username">null the function uses the default user name (The user context for the process provides the default user name)</param>
    /// <param name="flags"></param>
    /// <returns></returns>
    [DllImport("mpr.dll")]
    //public static extern int WNetAddConnection2(ref NETRESOURCE netResource, string password, string username, int flags);
    private static extern int WNetAddConnection2([In] NETRESOURCE netResource, string password, string username, int flags);
    /// <summary>
    /// to disconnect the networksource
    /// </summary>
    /// <param name="lpName"></param>
    /// <param name="dwFlags"></param>
    /// <param name="bForce"></param>
    /// <returns></returns>
    [DllImport("mpr.dll")]
    private static extern int WNetCancelConnection2(string lpName, Int32 dwFlags, bool bForce);
    /// <param name="nBufferLength"></param>
    /// <param name="lpBuffer"></param>
    /// <returns></returns>
    [DllImport("kernel32.dll")]
    private static extern uint GetLogicalDriveStrings(uint nBufferLength, [Out] char[] lpBuffer);
    #endregion

    #region enums/structs
    /// <example>
    /// NETRESOURCE myNetResource = new NETRESOURCE();
    /// myNetResource.dwScope = 2;
    /// myNetResource.dwType = 1;
    /// myNetResource.dwDisplayType = 3;
    /// myNetResource.dwUsage = 1;
    /// myNetResource.LocalName = "z:";
    /// myNetResource.RemoteName = @"\servername\sharename";
    /// myNetResource.Provider = null;
    /// </example>
    [StructLayout(LayoutKind.Sequential)]
    public class NETRESOURCE
    {
        public ResourceScope dwScope = 0;
        public ResourceType dwType = 0;
        public ResourceDisplayType dwDisplayType = 0;
        public ResourceUsage dwUsage = 0;
        public string lpLocalName = null;
        public string lpRemoteName = null;
        public string lpComment = null;
        public string lpProvider = null;
    };
    public enum ResourceScope : int
    {
        RESOURCE_CONNECTED = 1,
        RESOURCE_GLOBALNET,
        RESOURCE_REMEMBERED,
        RESOURCE_RECENT,
        RESOURCE_CONTEXT
    };
    public enum ResourceType : int
    {
        RESOURCETYPE_ANY,
        RESOURCETYPE_DISK,
        RESOURCETYPE_PRINT,
        RESOURCETYPE_RESERVED
    };
    public enum ResourceUsage
    {
        RESOURCEUSAGE_CONNECTABLE = 0x00000001,
        RESOURCEUSAGE_CONTAINER = 0x00000002,
        RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
        RESOURCEUSAGE_SIBLING = 0x00000008,
        RESOURCEUSAGE_ATTACHED = 0x00000010,
        RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED),
    };
    public enum ResourceDisplayType
    {
        RESOURCEDISPLAYTYPE_GENERIC,
        RESOURCEDISPLAYTYPE_DOMAIN,
        RESOURCEDISPLAYTYPE_SERVER,
        RESOURCEDISPLAYTYPE_SHARE,
        RESOURCEDISPLAYTYPE_FILE,
        RESOURCEDISPLAYTYPE_GROUP,
        RESOURCEDISPLAYTYPE_NETWORK,
        RESOURCEDISPLAYTYPE_ROOT,
        RESOURCEDISPLAYTYPE_SHAREADMIN,
        RESOURCEDISPLAYTYPE_DIRECTORY,
        RESOURCEDISPLAYTYPE_TREE,
        RESOURCEDISPLAYTYPE_NDSCONTAINER
    };
    #endregion

    #region IDisposable Members
    public void Dispose()
    {
        Dispose(true);
    }
    #endregion

    #region overrides/virtuals
    public override string ToString()
    {
        return m_FullDriveLetter;
    }
    /// <param name="disposing"></param>
    protected virtual void Dispose(bool disposing)
    {
        if (!m_Disposed)
        {
            if (disposing)
            {
                DisconnectNetworkDrive();
            }
            m_Disposed = true;
        }
    }
    #endregion
}

}

NetWorkUNCPath.cs 源代码:

using System;
using System.Management;
namespace SeekCopySupportTool.Business
{

public class NetWorkUNCPath
{
    // get UNC path
    public static string GetUNCPath(string path)
    {
        if (path.StartsWith(@"\\"))
        {
            return path;
        }

        ManagementObject mo = new ManagementObject();
        mo.Path = new ManagementPath(String.Format("Win32_LogicalDisk='{0}'", path));

        // DriveType 4 = Network Drive
        if (Convert.ToUInt32(mo["DriveType"]) == 4)
        {
            return Convert.ToString(mo["ProviderName"]);
        }
        // DriveType 3 = Local Drive
        else if (Convert.ToUInt32(mo["DriveType"]) == 3)
        {
            return "\\\\" + Environment.MachineName + "\\" + path.Substring(0,1) + "$";
        }
        else
        {
            return path;
        }
    }
}

}

答案 8 :(得分:0)

在C#对我来说,这是一种解决方法:

/*make long path short by setting it to like cd*/
string path = @"\\godDamnLong\Path\";
Directory.SetCurrentDirectory(path);

答案 9 :(得分:0)

我惊讶地发现 Jason 的解决方案在我的 PC 上使用 Visual Studio 2019 和 .Net Framework 4.7.2 运行良好

最初,我写了一些类似于此代码的内容

Dim sBaseDir = "D:\Documents\+Informatique\Application\@Visual Basic.NET\GetTestAchatsPosts\Site\communication-multimedia\ordinateurs"
Dim sLastDir = "2638.pc-acer-ne-charge-plus-malgre-un-retour-en-garantie-reviens-charge-mais-ne-charge-toujours-pas-garantie-passee-plus-dintervention-gra"

System.IO.Directory.CreateDirectory(sBaseDir & "\" & sLastDir)

此代码生成错误 429-PathTooLongException


然后我测试是只创建最后一个目录

System.IO.Directory.SetCurrentDirectory(sBaseDir)
System.IO.Directory.CreateDirectory(sLastDir)

此代码返回相同的错误 429-PathTooLongException


然后我使用一个短的基本目录进行了测试,以查看问题是否与最后一个目录或完整目录的长度有关

System.IO.Directory.SetCurrentDirectory("D:\Documents")
System.IO.Directory.CreateDirectory(sLastDir)

此代码有效。但是目录是在错误的位置创建的。


然后我测试了减少最后一个目录的名称长度。

System.IO.Directory.SetCurrentDirectory(sBaseDir)
System.IO.Directory.CreateDirectory(sLastDir.Substring(0, 100))

此代码有效,但最后的目录名称减少了!


然后我分两步使用 Jason 的建议进行了测试

System.IO.Directory.SetCurrentDirectory(sBaseDir)
System.IO.Directory.CreateDirectory("\\?\" & sLastDir)

此代码崩溃表明目录语法不正确!


然后我还测试了添加“.”的相同语法。字符串

System.IO.Directory.SetCurrentDirectory(sBaseDir)
System.IO.Directory.CreateDirectory("\\?\.\" & sLastDir)

此代码崩溃表明目录语法不正确!


然后我使用一个简单的命令在完整目录前加上 "\\?"

进行测试
System.IO.Directory.CreateDirectory("\\?\" & sBaseDir & "\" & sLastDir)

这段代码运行良好,对我来说是最好的解决方案。

唯一的不便是目录必须是完整目录。

警告!不能混用“\”和“/”字符!

我写了以下代码

sQuestionDir = "\\?\" & sArticleDir & "/" & sQuestionDir
If Not System.IO.Directory.Exists(sQuestionDir) Then
    System.IO.Directory.CreateDirectory(sQuestionDir)
End If

和程序在执行 CreateDirectory() function !

时崩溃

正确的代码是

sQuestionDir = "\\?\" & sArticleDir & "/" & sQuestionDir
If Not System.IO.Directory.Exists(sQuestionDir) Then
    System.IO.Directory.CreateDirectory(sQuestionDir)
End If

我希望所有这些测试都能帮助其他人解决他们的问题。