2009-06-28 39 views
4

有谁知道通过目录和子文件夹来枚举枚举中所有文件的更快方法吗?这就是我现在所拥有的:快速枚举包括子文件夹在内的所有文件的方法

Public Shared allFiles() As String 
allFiles = Directory.GetFiles(<ServerLocation>, "*.*", SearchOption.AllDirectories) 

谢谢! JFV

编辑:我从服务器位置枚举这些文件。我不知道这是否会改变这个问题的观点。感谢所有迄今为止的输入!

回答

4

简短的回答:

如果此代码是为您的项目功能正确,你还没有证明它是具有探查问题,那么不要改变它。继续使用功能正确的解决方案,直到证明它很慢。

龙答:

如何涨快跌慢的代码这个特殊的一块是取决于多种因素的很多。其中许多将取决于您正在运行的特定机器(例如硬盘驱动器的速度)。查看涉及文件系统的代码,而没有其他任何代码,很难说“x比y更快”并且具有一定的确定性。

在这种情况下,我只能真正评论一件事情。此方法的返回类型是FileInfo值的数组。数组需要连续的内存,非常大的数组可能会导致堆中的碎片问题。如果您有极其您正在阅读的大型目录可能导致堆碎片化和间接性能问题。

如果事实证明是一个问题,那么你可以PInvoke到FindFirstFile/FindNextFile并一次获得一个。结果在CPU周期中功能上可能较慢,但内存压力较小。

但我必须强调,你应该证明这些都是你修复之前的问题。

+0

+1好多表达比我能 – 2009-06-28 04:44:18

+0

然而,在同一时间,谁曾试图列出与.NET大型目录中的所有文件都会知道,这是一个性能问题。列出1000个文件夹名称,只是文件夹名称,可能需要几乎整整一秒。 – 2009-06-28 05:05:52

0

这是一个粗糙的做法。

dir /s /b 

得到这个输出到一个文本文件,通过\r\n阅读&分裂。
在特定的目录中运行上述命令,看看它是否有帮助。

只获取目录

dir /s /b /ad 

只获取文件

dir /s /b /a-d 

编辑:贾里德说得很不使用其他方法,除非你的方法证明缓慢。

3

using System.Collections.Generic;

private static List<string> GetFilesRecursive(string b) 
{ 

      // 1. 
      // Store results in the file results list. 
      List<string> result = new List<string>(); 

      // 2. 
      // Store a stack of our directories. 
      Stack<string> stack = new Stack<string>(); 

      // 3. 
      // Add initial directory. 
      stack.Push(b); 

      // 4. 
      // Continue while there are directories to process 
      while (stack.Count > 0) 
      { 
       // A. 
       // Get top directory 
       string dir = stack.Pop(); 

       try 
       { 
        // B 
        // Add all files at this directory to the result List. 
        result.AddRange(Directory.GetFiles(dir, "*.*")); 

        // C 
        // Add all directories at this directory. 
        foreach (string dn in Directory.GetDirectories(dir)) 
        { 
         stack.Push(dn); 
        } 
       } 
       catch 
       { 
        // D 
        // Could not open the directory 
       } 
      } 
      return result; 
     } 

道具原创文章:http://www.codeproject.com/KB/cs/workerthread.aspx

0

继承人我的解决方案。最初的启动有点慢,我正在努力。 my.computer.filesystem对象可能是缓慢启动的问题。但是这种方法将通过网络在5分钟内列出31,000个文件。

Imports System.Threading 

Public Class ThreadWork 

Public Shared Sub DoWork() 
    Dim i As Integer = 1 
    For Each File As String In My.Computer.FileSystem.GetFiles("\\172.16.1.66\usr2\syscon\S4_650\production\base_prog", FileIO.SearchOption.SearchTopLevelOnly, "*.S4") 
     Console.WriteLine(i & ". " & File) 
     i += 1 
    Next 
End Sub 'DoWork 
End Class 'ThreadWork 

Module Module1 

Sub Main() 
    Dim myThreadDelegate As New ThreadStart(AddressOf ThreadWork.DoWork) 
    Dim myThread As New Thread(myThreadDelegate) 
    myThread.Start() 
    '"Pause" the console to read the data. 
    Console.ReadLine() 
End Sub 'Main 

End Module 
相关问题