【问题标题】:Check if a file exist in directory or subdirectory [duplicate]检查目录或子目录中是否存在文件[重复]
【发布时间】:2013-04-07 10:16:55
【问题描述】:

我想检查一个文件是否存在于目录或子目录中。

string[] filePaths = Directory.GetFiles(padserver, "*", SearchOption.AllDirectories);
try {
    DataContainer.bestaatal = false;
    lusfilebestaat = 0;
    while (DataContainer.bestaatal == false) {
        filePaths[lusfilebestaat] = Path.GetFileName(filePaths[lusfilebestaat]);
        if (filePaths[lusfilebestaat] == bestandsnaam) {
            DataContainer.bestaatal = true;
        }
        lusfilebestaat = lusfilebestaat + 1;
    }
}

这可行,但速度很慢,因为我的服务器上有很多文件。

有没有人可以解决这个问题?

【问题讨论】:

  • bestandsnaam 是什么?
  • 这是文件名
  • 在 SO 中发布问题之前请先进行研究
  • 我也阅读了其他论坛主题,但我没有为我的项目找到解决方案
  • 您可以通过 P/Invoking FindFirstFileEx 轻松完成

标签: c# file-exists


【解决方案1】:

这可能对你有帮助

internal static bool FileOrDirectoryExists(string name)
{
   return (Directory.Exists(name) || File.Exists(name))
}

或者另一种方法是自己编写搜索功能,其中一个应该可以工作:

private bool FileExists(string rootpath, string filename)
{
    if(File.Exists(Path.Combine(rootpath, filename)))
        return true;

    foreach(string subDir in Directory.GetDirectories(rootpath, "*", SearchOption.AllDirectories))
    {
        if(File.Exists(Path.Combine(rootpath, filename)))
        return true;
    }

    return false;
}

private bool FileExistsRecursive(string rootPath, string filename)
{
    if(File.Exists(Path.Combine(rootPath, filename)))
        return true;

    foreach (string subDir in Directory.GetDirectories(rootPath))
    {
        return FileExistsRecursive(subDir, filename);
    }

    return false;
}

第一个仍然首先提取所有目录名称,因此如果有很多子目录并且文件靠近顶部,则可能会很慢。

第二种是递归的,在“最坏情况”的情况下可能会更慢,但如果有许多嵌套的子目录并且文件位于顶级目录中,则会更快。

【讨论】:

【解决方案2】:

使用System.IO.File.Exists() 方法。见msdn

【讨论】:

  • 虽然这也扫描子目录?
  • @Joeri 您为其提供的路径必须是完整的。
  • @Joeri 您必须传递文件的路径。 test.txt 绝对不会为你搜索子目录。
  • 我有 100 多个子文件夹。那样不行吗?
  • @Joeri 你到底想做什么?搜索您不知道它在哪里的特定文件?在这种情况下,“慢”是你必须忍受的(除非你的服务器有很多 SSD)。但是,如果您知道它应该在哪里,那么这是最好的答案。
猜你喜欢
  • 2013-04-24
  • 2012-05-17
  • 2011-04-29
  • 2013-11-30
  • 1970-01-01
  • 2017-06-11
  • 2016-09-26
  • 2011-03-16
  • 1970-01-01
相关资源
最近更新 更多