所以这段代码只给我文件夹名称。我需要同时获取文件夹和文件名:
Imports System
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each Dir As String In Directory.GetDirectories("c:\")
ListBox1.Items.Add(Dir)
Next
End Sub
End Class
我只获得文件夹名称,如下所示:
c:\$Recycle.Bin
c:\Boot
c:\Config.Msi
c:\Desktop
c:\Documents and Settings
c:\Program Files
c:\Program Files (x86)
c:\ProgramData
c:\System Volume Information
c:\Users
c:\Windows
答案 0 :(得分:3)
如果只想执行一个循环,那么可以使用DirectoryInfo类及其EnumerateFileSystemInfos
方法
Sub Main
Dim di = new DirectoryInfo("D:\temp")
for each fi in di.EnumerateFileSystemInfos()
if (fi.Attributes & FileAttributes.Directory) = FileAttributes.Directory Then
Console.WriteLine(fi.FullName + " is a directory")
else
Console.WriteLine(fi.FullName + " is a file")
End If
Next
End Sub
EnumerateFileSystemInfo
方法允许在不加载内存中的整个文件和目录集的情况下启动文件和目录的枚举。因此,如果您有许多文件和目录,这种方法可能更有效
为了论证,我还应该提到方法Directory.EnumerateFileSystemEntries
此方法不会构建DirectoryInfo
对象,因此它更快,但是,当然,您无法轻易区分返回的字符串之一是文件还是目录
For each name in Directory.EnumerateFileSystemEntries("D:\temp")
Console.WriteLine(name)
Next
答案 1 :(得分:1)
获取必须使用的文件Directory.GetFiles("C:\")
Imports System
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each Dir As String In Directory.GetDirectories("c:\")
ListBox1.Items.Add(Dir)
Next
For Each Dir As String In Directory.GetFiles("c:\")
ListBox1.Items.Add(Dir)
Next
End Sub
End Class