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

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

谢谢! JFV

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

有帮助吗?

解决方案

简短答案:

如果此代码在功能上对您的项目是正确的,并且您还没有证明这是探测师的问题,则不要更改它。继续使用功能上正确的解决方案,直到您证明其慢。

长答案:

该特定代码的速度或放慢程度取决于 很多 因素。其中许多将取决于您正在运行的特定机器(例如硬盘驱动器速度)。查看涉及文件系统的代码,没有其他内容,很难说“ x比y快”,并具有任何确定性。

在这种情况下,我只能对一件事进行评论。此方法的返回类型是FileInfo值的数组。阵列需要连续的内存,并且非常大的数组可能会在堆中引起碎裂问题。如果你有 极其 您正在阅读的大型目录可能会导致堆积分裂和间接性能问题。

如果事实证明这是一个问题,那么您可以将Findfirstfile / findNextfile固定并一次固定。在CPU周期中,结果可能会较慢,但记忆压力将较小。

但是我必须强调,您应该在您面前证明这些问题 使固定 他们。

其他提示

使用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

这是一种粗略的做法。

dir /s /b

将其输出到文本文件中,阅读并通过 \r\n.
在特定目录中运行上述命令,以查看是否有帮助。

仅获取目录

dir /s /b /ad

仅获取文件

dir /s /b /a-d

编辑:贾里德(Jared)说不要使用其他方法是正确的,除非您的方法被证明缓慢。

这是我的解决方案。初始启动有点慢,我正在为此努力。 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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top