gpt4 book ai didi

c# - 当路径太长时,File.Exists() 错误地返回 false

转载 作者:可可西里 更新时间:2023-11-01 07:42:51 30 4
gpt4 key购买 nike

我目前正在开发一个遍历各种目录的程序,以确保使用 File.Exists() 存在特定文件。

应用程序一直声称某些文件不存在,而实际存在,我最近发现这个错误是由于路径太长造成的。

我知道有一些关于 SO 的问题可以解决 File.Exists() 返回不正确的值,但似乎没有一个可以解决这个特定问题。

重命名目录和文件以缩短路径并不是一个真正的选择,所以我现在不确定该怎么做。是否有解决此问题的变通方法?

正在使用的代码没什么特别的(我删除了一些不相关的代码),但我会在下面包含它以防万一。

    private void checkFile(string path)
{
if (!File.Exists(path))
Console.WriteLine(" * File: " + path + " does not exist.");
}

最佳答案

这很丑陋且效率低下,但它确实绕过了 MAX_PATH 限制:

const int MAX_PATH = 260;

private static void checkPath(string path)
{
if (path.Length >= MAX_PATH)
{
checkFile_LongPath(path);
}
else if (!File.Exists(path))
{
Console.WriteLine(" * File: " + path + " does not exist.");
}
}

这里是 checkFile_LongPath 函数:

private static void checkFile_LongPath(string path)
{
string[] subpaths = path.Split('\\');
StringBuilder sbNewPath = new StringBuilder(subpaths[0]);
// Build longest subpath that is less than MAX_PATH characters
for (int i = 1; i < subpaths.Length; i++)
{
if (sbNewPath.Length + subpaths[i].Length >= MAX_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)
{
foundMatch = false;
// 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])
{
foundMatch = true;
break;
}
}
}
}
// If we didn't find a match, write to the console.
if (!foundMatch)
{
Console.WriteLine(" * File: " + path + " does not exist.");
}
}

关于c# - 当路径太长时,File.Exists() 错误地返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11210408/

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