两种方式遍历文件夹

两种方式遍历文件夹

我用两种方式遍历文件夹,一种就是用FOR EACH普通的编程技巧. 第二种是用Composite.
比较两种方式,觉得Composite要复杂的多,代码也多.
也没觉得有什么好处, 可能这么简单情况根本就不应该使用模式
请大家解释解释我这里如果用Composite是不是真的一点的好处也没有. 谢谢了

第一种代码如下:
Imports System
Imports System.IO
Module Module1
Sub Main()
Dim objListAll As New ListDir
Console.WriteLine("C:\Drivers")
objListAll.ListAll( New DirectoryInfo("C:\Drivers"), " ")
Console.ReadLine()
End Sub
End Module

Class ListDir
Shared intentLevel As Int16
Shared Sub ListAll( ByVal source As DirectoryInfo, ByVal INTENT As String )
intentLevel += 1
' Copy each file into it's new directory.
For Each fi As FileInfo In source.GetFiles()
Console.WriteLine(" ".PadLeft(intentLevel) & fi.Name)
Next
' Copy each subdirectory using recursion.
For Each diSourceSubDir As DirectoryInfo In source.GetDirectories()
Console.WriteLine("+".PadLeft(intentLevel) & diSourceSubDir.ToString)
ListAll(diSourceSubDir, " ".PadLeft(intentLevel))
intentLevel -= 1
Next
End Sub
End Class

第二种代码如下:

Imports System

Imports System.Collections

Imports System.IO

Module Module1

Sub Main()

Dim root As Composite = New Composite("C:\Drivers")

Dim comp As Composite = New Composite("A")

comp.Add(root)

Console.Read()

End Sub

End Module

' "Component"

Public MustInherit Class Component

Public name As String

' Constructor

Public Sub New(ByVal name As String)

Me.name = name

End Sub

Public Overridable Sub Add(ByVal c As Component)

End Sub

End Class

' "Leaf"

Class Leaf

Inherits Component

Public Sub New(ByVal name As String)

MyBase.New(name)

End Sub

Public Overrides Sub Add(ByVal c As Component)

Me.Add(c)

End Sub

End Class

'"Composite"

Class Composite

Inherits Component

Public Sub New(ByVal name As String)

MyBase.New(name)

End Sub

Private children As ArrayList = New ArrayList

Public Overrides Sub Add(ByVal c As Component)

If Directory.Exists(c.name) Then

Dim stringDirecotrys As String() = Directory.GetDirectories(c.name)

For Each stringDirectory As String In stringDirecotrys

Dim directory As Composite = New Composite(stringDirectory)

Console.WriteLine(stringDirectory)

Me.Add(Directory)

Next

End If

Dim stringFiles As String() = directory.GetFiles(c.name)

For Each stringFile As String In stringFiles

Dim file As Leaf = New Leaf(stringFile)

Console.WriteLine(stringFile)

children.Add(File)

Next

End Sub

End Class

转载于:https://www.cnblogs.com/yangbin990/archive/2007/12/13/994019.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值