|
Khi lập trình với VB, hẳn bạn đã gặp phải vấn đề tìm
kiếm một tập tin nào đó trên đĩa. Để giải quyết vấn
đề, ta thường dùng các hàm Win32 API. Tuy nhiên, khi
thử dùng các hàm trong thư viện FileSystemObject
(FSO) của VB, tôi thấy mọi việc trở nên thật dễ
dàng. |
|
Để thử nghiệm, bạn hãy tạo một dự án mới (Standard
Exe). Trong Form1 (được tạo ra theo mặc
định), bạn thêm một CommandButton, một
Label đủ lớn (dùng để hiển thị tên thư mục hiện
hành) và một ListBox để liệt kê kết quả. |
|
Đoạn mã 1
Option Explicit
Dim fso As New FileSystemObject ‘Tạo đối tượng
FileSystemObject
Dim fld As Folder
Private Sub Command1_Click()
Dim nDirs As Integer, nFiles As Integer, lSize As
Long
Dim sDir As String, sSrchString As String
sDir = InputBox("Nhập tên đường dẫn: ", _
"Test", "C:\") ‘mặc định là C:\
sSrchString = InputBox("Nhập tên tập tin cần tìm: ",
_
"FileSystemObjects example", "Msvcrt.dll") ‘mặc
định là Msvcrt.dll
MousePointer = vbHourglass
Label1.Caption = "Thư mục " & vbCrLf & UCase(sDir) &
"..."
lSize = FindFile(sDir, sSrchString, nDirs, nFiles)
MousePointer = vbDefault
MsgBox “Tìm thấy “ & Str(nFiles) & " tập tin trong "
& Str(nDirs) _
& “thư mục ", vbInformation
MsgBox "Tổng cộng = " & lSize & " bytes"
End Sub
Private Function FindFile(ByVal sFol As String,
sFile As String, _
nDirs As Integer, nFiles As Integer) As Long
Dim tFld As Folder, tFil As File, FileName As String
Set fld = fso.GetFolder(sFol)
FileName = Dir(fso.BuildPath(fld.Path, sFile),
vbNormal Or _
vbHidden Or vbSystem Or vbReadOnly)
While Len(FileName) <> 0
FindFile = FindFile +
FileLen(fso.BuildPath(fld.Path, FileName))
nFiles = nFiles + 1
List1.AddItem fso.BuildPath(fld.Path, FileName)
‘Thêm vào list
FileName = Dir() 'Tìm tiếp ...
DoEvents
Wend
Label1 = " Thư mục " & vbCrLf & fld.Path & "..."
nDirs = nDirs + 1
If fld.SubFolders.Count > 0 Then
For Each tFld In fld.SubFolders
DoEvents
FindFile = FindFile + FindFile(tFld.Path, sFile,
nDirs, nFiles)
Next
End If
End Function |