vb.net 如何正确计算文件夹中的文件数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15866808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to correctly count the number of files in a folder
提问by David Gard
I am making a list of folders, where each folder needs only a few properties, so I'm using the Class below. However, no matter the folder, the FilesInFolder
property is alway 5 more than the actual number of files in the folder.
我正在制作一个文件夹列表,其中每个文件夹只需要几个属性,所以我使用下面的类。但是,无论文件夹如何,该FilesInFolder
属性始终比文件夹中的实际文件数多 5。
Can someone please help me find out what is wrong? Thanks.
有人可以帮我找出问题所在吗?谢谢。
Public Class Single_Action_Folder
Public ReadOnly FullName As String = ""
Public ReadOnly Name As String = ""
Public ReadOnly FilesInFolder As Integer = 0
Public ReadOnly Exists As Boolean = False
'**
' Constructor
'*
Public Sub New(Optional dir As DirectoryInfo = Nothing)
' First check that a directory has been specified
If dir Is Nothing Then Exit Sub
' Populate the class properties
FullName = dir.FullName
Name = dir.Name
FilesInFolder = dir.GetFiles().Count
Exists = dir.Exists
End Sub
End Class
回答by David Gard
So the issue here is that FilesInFolder = dir.GetFiles().Count
was counting hidden files. Even though I've set Windows folder options to show hidden files/folders, they were not shown as they were things like album art. The following line sorted my issue.
所以这里的问题FilesInFolder = dir.GetFiles().Count
是计算隐藏文件。即使我已经设置了 Windows 文件夹选项来显示隐藏的文件/文件夹,它们也没有显示出来,因为它们是像专辑封面这样的东西。以下行对我的问题进行了排序。
FilesInFolder = Directory.GetFiles(FullName, "*.mp3").Count
I am wondering though, if there is a way to count more than one file type? I.e MP3 and WMA? If anyone happens to know, I'd apprciate a comment.
我想知道,是否有办法计算多个文件类型?即 MP3 和 WMA?如果有人碰巧知道,我会发表评论。
回答by Piotr Stapp
Check you do not have hidden files in tested directories. I check your code on my PC and it is working good.
检查您在测试目录中没有隐藏文件。我在我的电脑上检查了你的代码,它运行良好。
回答by CreeperPower storing
use this code:
使用此代码:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim FilesInFolder = Directory.GetFiles("C:\BGS\TemporaryProjects\Images\", "*.mp3").Count
Dim i As Integer = 1
While i <= FilesInFolder
ListBox1.Items.Add(i)
i += 1
End While
End Sub