gpt4 book ai didi

c# - 替代 Directory.CreateDirectory(path) 支持长路径

转载 作者:太空狗 更新时间:2023-10-29 23:01:57 24 4
gpt4 key购买 nike

只是想知道是否有 Directory.CreateDirectory() 的替代方法,因为我正在尝试创建一个超过 260 个字符的目录,虽然文件名不长,但目录路径是.

如果有任何技巧,我可以指向 CreateDirectory 在此位置创建一个文件夹,而无需提供目录的完整路径。当我在文件夹中创建文件夹等等时。必须有一些合法的方法来做到这一点。

我现在保存在隐藏标签中的字符串有问题,所以它不再是问题了。

最佳答案

的简单解决方案是使用启用 unc 的路径, 将允许最多约 32767 个字符的文件路径

string longPathEnabledFileName = Path.ToLongPath("C:\SomeVeryLongPath\...."); 
FileStream fs = new FileStream(longPathEnabledFileName);

这将简单地在路径前加上\\?\,告诉框架绕过 260 个字符的 MAX_PATH 限制。 不幸的是,在撰写本文时(从 4.0 版开始),\\?\的前缀在 .Net 中不支持

这给我们留下了 WinApi 解决方案和引用 Kernel32.dll 以使用 SafeFileHandle。来自 BCL 团队的 Kim Hamilton 已经在博客上发布了一系列解决 MAX_PATH 限制的方法(第 2 部分展示了如何使用 winapi 函数),其中包含一个代码片段以供引用:

// This code snippet is provided under the Microsoft Permissive License.using System;using System.IO;using System.Runtime.InteropServices;using Microsoft.Win32.SafeHandles;[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]internal static extern SafeFileHandle CreateFile(    string lpFileName,    EFileAccess dwDesiredAccess,    EFileShare dwShareMode,    IntPtr lpSecurityAttributes,    ECreationDisposition dwCreationDisposition,    EFileAttributes dwFlagsAndAttributes,    IntPtr hTemplateFile);public static void TestCreateAndWrite(string fileName) {    string formattedName = @"\\?\" + fileName;    // Create a file with generic write access    SafeFileHandle fileHandle = CreateFile(formattedName,        EFileAccess.GenericWrite, EFileShare.None, IntPtr.Zero,        ECreationDisposition.CreateAlways, 0, IntPtr.Zero);    // Check for errors    int lastWin32Error = Marshal.GetLastWin32Error();    if (fileHandle.IsInvalid) {        throw new System.ComponentModel.Win32Exception(lastWin32Error);    }    // Pass the file handle to FileStream. FileStream will close the    // handle    using (FileStream fs = new FileStream(fileHandle,                                    FileAccess.Write)) {        fs.WriteByte(80);        fs.WriteByte(81);        fs.WriteByte(83);        fs.WriteByte(84);    }}

还有一个库将所有这些工作封装在谷歌代码中,称为 zeta long paths

关于c# - 替代 Directory.CreateDirectory(path) 支持长路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8755920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com