【问题标题】:Directory.GetFiles does not refresh the results/cacheDirectory.GetFiles 不刷新结果/缓存
【发布时间】:2014-09-25 17:38:47
【问题描述】:

我在递归扫描文件夹和查找文件时遇到问题。 一切正常,直到某些文件或文件夹发生更改。 它似乎永远不会更新文件夹列表缓存。

是否有刷新或清除缓存,所以它会重新扫描文件?

提前谢谢!

ArrayList list = new ArrayList();
void dirsearch(string sDir)
{
    try
    {
       foreach (string d in Directory.GetFiles(sDir)) 
       {
         foreach (string f in Directory.GetFiles(d, "*.txt"))
          {
             string foldername = new DirectoryInfo(d).Name;
              String filename = Path.GetFileName("c:\\" + f);
              list.Add("C:\\" + f);
              list.Add(foldername);
              list.Add(filename);
              MessageBox.Show("found one!");
          }
        dirsearch(d);
       }
    }
    catch (System.Exception excpt) 
    {
        MessageBox.Show(excpt.Message);
    }
}

【问题讨论】:

  • 我很怀疑这段代码能否正常工作。
  • Matthias 的回答非常棒。所有 GetFiles 都是 Directory 类中的一个方法。你调用它一次,然后它就完成了。如果您注意到 GetFiles 的返回类型是一个字符串数组,您就会明白这一点。

标签: c# caching directory refresh getfiles


【解决方案1】:

GetFiles 获取它在扫描时准确找到的文件。 没有跟踪变化。

您似乎需要 FileSystemWatcher 类,它会监视文件夹并触发一个事件,告诉您有关文件更改的信息。

更多详情见:http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher%28v=vs.110%29.aspx

【讨论】:

    【解决方案2】:

    可以使用GetFilesthis overload方法,不需要递归

    var files = Directory.GetFiles(sDir, "*.txt", SearchOption.AllDirectories);
    

    edit:修复了错字,堆栈溢出需要 6 个以上的字符编辑。

    【讨论】:

      猜你喜欢
      • 2015-01-03
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多