这可行,但需要更快地工作 [英] This Works But It Needs To Work Faster
问题描述
我已经弄清楚了如何在一个列表框中列出多个文件扩展名,但是我又回到了性能问题上.当我去加载C:\目录以查找.com和.sys文件时,填充列表框需要25秒钟.我可以使用文件流吗?或枚举?或背景工作者?有没有更快的搜索这些文件的方法?
到目前为止,我已经修改以适合我的需求的代码是:
I have figured out how to list multiple file extensions to a listbox but again I have come back to my problem with performance issues. When I go to load the C:\ directory to look for .com and .sys files it takes a good 25 seconds to populate the listbox. Can I use file stream? or enumerate? or a background worker? is there a faster way to search for these files?
the code I have so far that I have modified to suite my needs are this:
Imports System.IO
Public Class lstFiles
Dim strExts() As String = {".com", ".sys"}
Public Sub GetDirs(ByVal path As String, Optional ByVal getSubDirs As Boolean = True)
Try
For Each subDir As String In Directory.GetDirectories(path)
GetFiles(subDir)
If getSubDirs Then
GetDirs(subDir)
End If
Next
Catch ex As Exception
Debug.WriteLine(ex.ToString)
End Try
End Sub
Public Sub GetFiles(ByVal path As String)
Try
For Each strFile As String In Directory.GetFiles(path)
Dim fInfo As New FileInfo(strFile)
'If fInfo.Extension = ".png" Then
If strExts.Contains(fInfo.Extension) Then
listfiles.Items.Add(fInfo.FullName)
End If
Next
Catch ex As Exception
Debug.WriteLine(ex.ToString)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
GetDirs(ComboBox1.SelectedItem)
GetFiles(ComboBox1.SelectedItem)
Label2.Text = listfiles.Items.Count
End Sub
Private Sub lstFiles_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.Items.AddRange(System.IO.Directory.GetLogicalDrives)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
TextBox1.Text = ComboBox1.SelectedItem
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
listfiles.Items.Clear()
Label2.Text = 0
End Sub
End Class
这是执行此操作的最佳方法,还是可以不使用列表框以某种方式搜索多个文件扩展名?
预先谢谢您:)
Is this the best way to do this or can I somehow search for multiple file extensions without the use of a listbox?
Thank you in advance :)
推荐答案
您正在对整个c:驱动器进行递归搜索.在典型的系统上,这当然需要时间.与其他系统相比,25秒可能相当快.
并且,在发布时设置代码片段的格式.
You are doing a recursive search of the entire c: drive. On a typical system of course this will take time. 25 seconds could be quite fast compared to other systems.
And, format your code snippets when posting.
看看这篇出色的文章(我已经使用了很多):
更快的目录枚举器 [
Take a look at this excellent article (I have used it a lot):
A Faster Directory Enumerator[^]
EDIT : to filter the results
FileData[] resultsfromcall = FastDirectoryEnumerator.GetFiles("c:\\");
List<FileData> fd = new List<FileData>(resultfromcall);
var filtered = fd.FindAll(delegate(FileData f) { return f.Name.EndsWith(".sys") || f.Name.EndsWith(".com");});
这篇关于这可行,但需要更快地工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!