【问题标题】:Directory Traversal in C#C#中的目录遍历
【发布时间】:2008-11-19 09:32:24
【问题描述】:

如何使用 C# 遍历文件夹结构而不陷入junction points 的陷阱?

【问题讨论】:

    标签: c# ntfs


    【解决方案1】:

    对于那些不知道的人:连接点的行为类似于 linux 上文件夹的符号链接。当您设置递归文件夹结构时,会发生上述陷阱,如下所示:

    given folder /a/b
    let /a/b/c point to /a
    then
    /a/b/c/b/c/b becomes valid folder locations.
    

    我建议采用这样的策略。在 Windows 上,您被限制为路径字符串的最大长度,因此递归解决方案可能不会破坏堆栈。

    private void FindFilesRec(
        string newRootFolder,
        Predicate<FileInfo> fileMustBeProcessedP,
        Action<FileInfo> processFile)
    {
        var rootDir = new DirectoryInfo(newRootFolder);
        foreach (var file in from f in rootDir.GetFiles()
                             where fileMustBeProcessedP(f)
                             select f)
        {
            processFile(file);
        }
    
        foreach (var dir in from d in rootDir.GetDirectories()
                            where (d.Attributes & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint
                            select d)
        {
            FindFilesRec(
                dir.FullName,
                fileMustBeProcessedP,
                processFile);
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用以下代码:

      private void processing(string directory)
              {
                  cmbFilesTypesSelectedIndex = cmbFilesTypes.SelectedIndex;
                  CheckForProjectFile(directory);
                  DirectoryInfo dInfo = new DirectoryInfo(directory);
                  DirectoryInfo[] dirs = dInfo.GetDirectories() ;
                  foreach (DirectoryInfo subDir in dirs)
                  {
                      CheckForProjectFile(subDir.FullName);
                      processing(subDir.FullName);
                  }
              }
      
              private void CheckForProjectFile(string directory)
              {
                  Boolean flag = false; 
                  DirectoryInfo dirInfo = new DirectoryInfo(directory);
                  FileInfo[] files = dirInfo.GetFiles();
                  //You can also traverse in files also
                  foreach (FileInfo subfile in files)
                  {
                      //Do you want
      
                  }
              }
      

      【讨论】:

      • 我没有看到您在该代码的任何地方检查重解析点。因此,您实际上并没有避开陷阱。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 2015-11-19
      • 2016-07-24
      相关资源
      最近更新 更多