[英]Error: File Path is Too Long
i am trying to use the various file functions in C# like File.GetLastWriteTime
, copy command on the file placed at the path greater than maximum allowed path on windows 7 ie 260. Its giving me an error on long path name. 我试图在C#中使用各种文件函数,如File.GetLastWriteTime
,复制命令放在路径上的文件大于Windows 7上的最大允许路径,即260.它给我一个长路径名错误。 On MSDN support i they have asked to use the \\\\?\\
before the path. 在MSDN支持上,他们要求在路径前使用\\\\?\\
。 I did the same but still i got the same error, it seems it doesn't make any change. 我做了同样的但仍然得到了同样的错误,它似乎没有做任何改变。 Below is my code. 以下是我的代码。 Please let me know if i am using it correct or i need to add any thing: 如果我使用它正确或我需要添加任何东西,请告诉我:
These all lib i am using as the code is having other things also: 我使用的所有lib作为代码还有其他东西:
the below is the respective code: 以下是各自的代码:
filesToBeCopied = Directory.GetFiles(path,"*",SearchOption.AllDirectories);
for (int j = 0; j < filesToBeCopied.Length; j++)
{
try
{
String filepath = @"\\?\" + filesToBeCopied[j];
File.GetLastWriteTime(filepath);
}
catch (Exception ex)
{
MessageBox.Show("Error Inside the single file iteration for the path:" +
filesToBeCopied[j] + " . The exception is :" + ex.Message);
}
}
where as path is the path to the folder at windows machine starting with drive letter. 其中path是Windows机器上以驱动器号开头的文件夹的路径。 for ex.: d:\\abc\\bcd\\cd\\cdc\\dc\\..........
例如: d:\\abc\\bcd\\cd\\cdc\\dc\\..........
Here's a solution for at least the copying portion of your request (thank you pinvoke.net ): 这是至少您的请求的复制部分的解决方案(谢谢pinvoke.net ):
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static extern bool CopyFile(string lpExistingFileName, string lpNewFileName, bool bFailIfExists);
And then to actually copy your file: 然后实际复制你的文件:
// Don't forget the '\\?\' for long paths
string reallyLongPath = @"\\?\d:\abc\bcd\cd\cdc\dc\..........";
string destination = @"C:\some\other\path\filename.txt";
CopyFile(reallyLongPath , destination, false);
As far as I know, you can't access a file directly if its path is too long (by directly, I mean using the methods of File
, by creating a FileInfo
via the constructor, or by using Directory.GetFiles(string fileName)
. 据我所知,如果文件的路径太长,则无法直接访问文件(直接使用File
的方法,通过构造函数创建FileInfo
,或使用Directory.GetFiles(string fileName)
。
The only way I've found that will let you access such a file is to access a directory somewhere in the path before it gets too long, and then programatically walk down the tree until you get to your file, as seen here . 我发现的唯一方法,可以让你访问这样的文件是在某处访问的目录路径它变得不久,然后编程走在树,直到你得到你的文件,因为看到这里 。
I've taken my code from there and modified it a little to return a FileInfo
object for a file with a path that is "too long". 我从那里获取了我的代码并对其进行了一些修改以返回一个FileInfo
对象,该文件的路径为“太长”。 Using this code, you can access the necessary properties on the returned FileInfo
object (like LastWriteTime
). 使用此代码,您可以在返回的FileInfo
对象(如LastWriteTime
)上访问必要的属性 。 It still has some limitations though, like the inability to use functions like CopyTo()
or OpenText()
. 它仍然有一些局限性,比如无法使用CopyTo()
或OpenText()
等函数。
// Only call GetFileWithLongPath() if the path is too long
// ... otherwise, new FileInfo() is sufficient
private static FileInfo GetFile(string path)
{
if (path.Length >= MAX_FILE_PATH)
{
return GetFileWithLongPath(path);
}
else return new FileInfo(path);
}
static int MAX_FILE_PATH = 260;
static int MAX_DIR_PATH = 248;
private static FileInfo GetFileWithLongPath(string path)
{
string[] subpaths = path.Split('\\');
StringBuilder sbNewPath = new StringBuilder(subpaths[0]);
// Build longest sub-path that is less than MAX_PATH characters
for (int i = 1; i < subpaths.Length; i++)
{
if (sbNewPath.Length + subpaths[i].Length >= MAX_DIR_PATH)
{
subpaths = subpaths.Skip(i).ToArray();
break;
}
sbNewPath.Append("\\" + subpaths[i]);
}
DirectoryInfo dir = new DirectoryInfo(sbNewPath.ToString());
bool foundMatch = dir.Exists;
if (foundMatch)
{
// Make sure that all of the subdirectories in our path exist.
// Skip the last entry in subpaths, since it is our filename.
// If we try to specify the path in dir.GetDirectories(),
// We get a max path length error.
int i = 0;
while (i < subpaths.Length - 1 && foundMatch)
{
foundMatch = false;
foreach (DirectoryInfo subDir in dir.GetDirectories())
{
if (subDir.Name == subpaths[i])
{
// Move on to the next subDirectory
dir = subDir;
foundMatch = true;
break;
}
}
i++;
}
if (foundMatch)
{
// Now that we've gone through all of the subpaths, see if our file exists.
// Once again, If we try to specify the path in dir.GetFiles(),
// we get a max path length error.
foreach (FileInfo fi in dir.GetFiles())
{
if (fi.Name == subpaths[subpaths.Length - 1])
{
return fi;
}
}
}
}
// If we didn't find a match, return null;
return null;
}
Now that you've seen that, go rinse your eyes and shorten your paths. 既然你已经看到了,那就去冲洗你的眼睛并缩短你的路径。
try with this code 尝试使用此代码
var path = Path.Combine(@"\\?\", filesToBeCopied[j]); //don't forget extension
"\\?\\" prefix to a path string tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system. 路径字符串的“\\?\\”前缀告诉Windows API禁用所有字符串解析并将其后面的字符串直接发送到文件系统。
Important : Not all file I/O APIs support "\\?\\", you should look at the reference topic for each API 重要提示:并非所有文件I / O API都支持“\\?\\”,您应该查看每个API的参考主题
http://www.codinghorror.com/blog/2006/11/filesystem-paths-how-long-is-too-long.html http://www.codinghorror.com/blog/2006/11/filesystem-paths-how-long-is-too-long.html
I recently imported some source code for a customer that exceeded the maximum path limit of 256 characters . 我最近为超过256个字符的最大路径限制的客户导入了一些源代码。
The path you pasted was 285 characters long. 您粘贴的路径长度为285个字符。
As you noted in your comment, MSDN's link here ( http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#maximum%5Fpath%5Flength ) explains this length in greater detail: 正如您在评论中所述,MSDN的链接( http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#maximum%5Fpath%5Flength )更详细地解释了这个长度:
In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters . 在Windows API中(以下段落中讨论了一些例外),路径的最大长度为MAX_PATH,定义为260个字符 。 A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. 本地路径按以下顺序构成:驱动器号,冒号,反斜杠,由反斜杠分隔的名称组件以及终止空字符。 For example, the maximum path on drive D is "D:\\some 256-character path string" where "" represents the invisible terminating null character for the current system codepage. 例如,驱动器D上的最大路径是“D:\\某个256个字符的路径字符串”,其中“”表示当前系统代码页的不可见的终止空字符。 (The characters < > are used here for visual clarity and cannot be part of a valid path string.) (这里使用字符<>是为了清晰,不能成为有效路径字符串的一部分。)
With respect to the \\\\?\\
functionality: 关于\\\\?\\
功能:
Many but not all file I/O APIs support "\\?\\"; 许多但不是所有文件I / O API都支持“\\?\\”; you should look at the reference topic for each API to be sure. 您应该查看每个API的参考主题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.