我无法复制一些文件夹260+字符(例如:使用标准DrectoryInfo.Create()将F:\NNNNNNNNNNNNNNNN\NNNNNNNNNNN\ROOT\$RECYCLE.BIN\S-1-5-21-3299053755-4209892151-505108915-1000\$RMSL3U8\NNNNNNNNN NNNNNNNN\NNNNNNNNNNN\NNNNNNNNNN\NNNNNNNNNN\publish\Application Files\TNNNNNNNNNNNN_1___0\NNNNNNNNNNNN.exe.manifest)添加到其他位置;添加\?\或\?\UNC\ (如"\?\UNC\") )只是抛出另一个ArgumentException。我做错了什么?不使用Directory.SetCurrentDirectory()我还能做什么?
发布于 2012-10-05 21:23:19
是的,使用标准API会给你这样的限制(255个字符IIRC)。
在.NET中,您可以使用AlphaFS project,它允许您使用非常长的路径(使用"\?\“样式)并模仿System.IO名称空间。
例如,您可以像使用System.IO.File.Copy()一样使用这个库,就像使用System.IO一样
如果您不想或不能使用AlphaFS,则必须调用Win32 API
发布于 2012-10-05 21:31:59
实际上,您需要从c#调用win32。我们已经做到了
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
public static class LongPath
{
static class Win32Native
{
[StructLayout(LayoutKind.Sequential)]
public class SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr pSecurityDescriptor;
public int bInheritHandle;
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CreateDirectory(string lpPathName, SECURITY_ATTRIBUTES lpSecurityAttributes);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
}
public static bool CreateDirectory(string path)
{
return Win32Native.CreateDirectory(String.Concat(@"\\?\", path), null);
}
public static FileStream Open(string path, FileMode mode, FileAccess access)
{
SafeFileHandle handle = Win32Native.CreateFile(String.Concat(@"\\?\", path), (int)0x10000000, FileShare.None, null, mode, (int)0x00000080, IntPtr.Zero);
if (handle.IsInvalid)
{
throw new System.ComponentModel.Win32Exception();
}
return new FileStream(handle, access);
}
}示例代码:
string path = @"c:\".PadRight(255, 'a');
LongPath.CreateDirectory(path);
path = String.Concat(path, @"\", "".PadRight(255, 'a'));
LongPath.CreateDirectory(path);
string filename = Path.Combine(path, "test.txt");
FileStream fs = LongPath.Open(filename, FileMode.CreateNew, FileAccess.Write);
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine("abc");
}发布于 2013-02-16 14:01:34
微软TechNet上有一个很棒的库,可以用来解决长文件名的问题,它叫做,并且它有自己的来自System.IO的关键方法的版本
例如,您可以替换:
System.IO.Directory.GetFiles使用
Delimon.Win32.IO.Directory.GetFiles它可以让你处理长文件和文件夹。
来自网站:
Dlimon.Win32.IO取代了System.IO的基本文件功能,并支持最多32,767个字符的文件和文件夹名称。
这个库是在.NET Framework4.0上编写的,可以在x86和x64系统上使用。标准System.IO命名空间的文件和文件夹限制可以处理文件名中包含260个字符、文件夹名中包含240个字符的文件(MAX_PATH通常配置为260个字符)。通常,您在使用标准.NET库时会遇到System.IO.PathTooLongException错误。
https://stackoverflow.com/questions/12747132
复制相似问题