Windows - Windows中的路径名(Directory Name)长度上限是248字节

可以用如下的C#代码可验证这个上限值。

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Chimomo's Company">
//   Respect the work.
// </copyright>
// <summary>
//   The program.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace CSharpLearning
{
    using System.IO;

    /// <summary>
    /// The program.
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// The main.
        /// </summary>
        public static void Main()
        {
            string directory = @"D:\";
            for (int i = 0; i < 122; i++)
            {
                directory += @"t\";
            }

            Directory.CreateDirectory(directory);
        }
    }
}
上面的代码中,字符串directory刚好是247个字节,再多加一个字符就会报错:

Unhandled Exception: System.IO.PathTooLongException: 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.
   at System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, Boolean checkHost)
   at System.IO.Directory.InternalCreateDirectoryHelper(String path, Boolean checkHost)
   at System.IO.Directory.CreateDirectory(String path)
   at CSharpLearning.Program.Main() in d:\My Project\Learning\CSharpLearning\CSharpLearning\Program.cs:line 24
Press any key to continue . . .

由此就验证了Windows中的路径长度上限是248字节(因为Windows在存储路径名时末尾还要加一个'\0')。但是,仍然可以手动做出一个路径长度大于248字节的一个路径,只需在上述用代码创建的路径中任意重命名一个文件夹,使其文件夹名字长度大于1字节即可。


相关文章
相关标签/搜索