<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="VB6Parse Library Reference - dir - File">
<title>dir - File - VB6Parse Library Reference</title>
<link rel="stylesheet" href="../../../assets/css/style.css">
<link rel="stylesheet" href="../../../assets/css/docs-style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<script src="../../../assets/js/theme-switcher.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/vbnet.min.js"></script>
<script>hljs.highlightAll();</script>
</head>
<body>
<header class="docs-header">
<div class="container">
<h1><a href="../../../index.html">VB6Parse</a> / <a href="../../../library/index.html">Library</a> / <a href="../../../library/functions/file/index.html">File</a> / dir</h1>
<p class="tagline">VB6 Library Reference</p>
</div>
</header>
<nav class="docs-nav">
<div class="container">
<a href="../../../index.html">Home</a>
<a href="../../../library/index.html">Library Reference</a>
<a href="../../../documentation.html">Documentation</a>
<a href="https://docs.rs/vb6parse" target="_blank">API Docs</a>
<a href="https://github.com/scriptandcompile/vb6parse" target="_blank">GitHub</a>
<button id="theme-toggle" class="theme-toggle" aria-label="Toggle theme">
<span class="theme-icon">🌙</span>
</button>
</div>
</nav>
<main class="container">
<article class="library-item">
<h1 id="dir-function">Dir Function</h1>
<p>Returns a <code>String</code> representing the name of a file, directory, or folder that matches a
specified pattern or file attribute, or the volume label of a drive.</p>
<h2 id="syntax">Syntax</h2>
<pre><code class="language-vbnet">Dir[(pathname[, attributes])]</code></pre>
<h2 id="parameters">Parameters</h2>
<ul>
<li><strong>pathname</strong>: Optional. <code>String</code> expression that specifies a file name, directory name,
or folder name. May include wildcards (* and ?). If not specified, uses the pattern
from the previous <code>Dir</code> call.</li>
<li><strong>attributes</strong>: Optional. Constant or numeric expression whose sum specifies file
attributes. If omitted, returns files that match pathname but have no attributes.</li>
</ul>
<h2 id="attributes">Attributes</h2>
<ul>
<li><strong>vbNormal</strong> (0): Normal files (default)</li>
<li><strong>vbReadOnly</strong> (1): Read-only files</li>
<li><strong>vbHidden</strong> (2): Hidden files</li>
<li><strong>vbSystem</strong> (4): System files</li>
<li><strong>vbVolume</strong> (8): Volume label (pathname ignored)</li>
<li><strong>vbDirectory</strong> (16): Directories or folders</li>
<li><strong>vbArchive</strong> (32): Files that have changed since last backup</li>
</ul>
<h2 id="return-value">Return Value</h2>
<p>Returns a <code>String</code> containing the name of a file, directory, or folder that matches the
specified pattern and attributes. Returns a zero-length string ("") when no more files
are found.</p>
<h2 id="remarks">Remarks</h2>
<p>The <code>Dir</code> function is used to retrieve file and directory names that match a pattern.
It's commonly used to iterate through files in a directory or to check if a file exists.
<strong>Important Characteristics:</strong>
- First call with pathname initializes search and returns first match
- Subsequent calls without arguments return next matching file
- Returns empty string ("") when no more matches found
- Case-insensitive pattern matching
- Supports wildcards: * (multiple chars) and ? (single char)
- Does not return "." and ".." directory entries
- Order of returned files is not guaranteed (typically file system order)
- Maintains internal state between calls
- Multiple Dir loops cannot be nested without complications
- Changing directory during Dir enumeration can cause issues</p>
<h2 id="wildcards">Wildcards</h2>
<ul>
<li><code>*</code> - Matches zero or more characters</li>
<li><code>?</code> - Matches exactly one character</li>
<li><code>*.*</code> - All files with extensions</li>
<li><code>*.txt</code> - All .txt files</li>
<li><code>test?.dat</code> - Files like test1.dat, testA.dat</li>
</ul>
<h2 id="examples">Examples</h2>
<h3 id="basic-usage">Basic Usage</h3>
<pre><code class="language-vbnet">' Get first .txt file in current directory
Dim fileName As String
fileName = Dir("*.txt")
MsgBox fileName
' Check if specific file exists
If Len(Dir("C:\data\report.txt")) > 0 Then
MsgBox "File exists"
End If
' Get volume label
Dim volumeLabel As String
volumeLabel = Dir("C:\", vbVolume)</code></pre>
<h3 id="iterate-through-files">Iterate Through Files</h3>
<pre><code class="language-vbnet">Sub ListAllTextFiles()
Dim fileName As String
' First call with pattern
fileName = Dir("C:\Documents\*.txt")
' Loop through all matches
Do While fileName <> ""
Debug.Print fileName
fileName = Dir ' Subsequent calls without arguments
Loop
End Sub</code></pre>
<h3 id="count-files">Count Files</h3>
<pre><code class="language-vbnet">Function CountFiles(path As String, pattern As String) As Long
Dim fileName As String
Dim count As Long
count = 0
fileName = Dir(path & "\" & pattern)
Do While fileName <> ""
count = count + 1
fileName = Dir
Loop
CountFiles = count
End Function</code></pre>
<h2 id="common-patterns">Common Patterns</h2>
<h3 id="file-existence-check">File Existence Check</h3>
<pre><code class="language-vbnet">Function FileExists(filePath As String) As Boolean
FileExists = (Len(Dir(filePath)) > 0)
End Function
' Usage
If FileExists("C:\data\file.txt") Then
' File exists
End If</code></pre>
<h3 id="get-all-files-in-directory">Get All Files in Directory</h3>
<pre><code class="language-vbnet">Function GetFileList(folderPath As String, pattern As String) As Variant
Dim files() As String
Dim fileName As String
Dim count As Long
count = 0
ReDim files(0 To 100)
fileName = Dir(folderPath & "\" & pattern)
Do While fileName <> ""
files(count) = fileName
count = count + 1
If count > UBound(files) Then
ReDim Preserve files(0 To UBound(files) + 100)
End If
fileName = Dir
Loop
If count > 0 Then
ReDim Preserve files(0 To count - 1)
GetFileList = files
Else
GetFileList = Array()
End If
End Function</code></pre>
<h3 id="find-files-by-attribute">Find Files by Attribute</h3>
<pre><code class="language-vbnet">Sub ListHiddenFiles(folderPath As String)
Dim fileName As String
fileName = Dir(folderPath & "\*.*", vbHidden)
Do While fileName <> ""
Debug.Print "Hidden: " & fileName
fileName = Dir
Loop
End Sub
Sub ListDirectories(folderPath As String)
Dim dirName As String
dirName = Dir(folderPath & "\*.*", vbDirectory)
Do While dirName <> ""
' Filter out "." and ".." if they appear
If dirName <> "." And dirName <> ".." Then
' Check if it's actually a directory
If GetAttr(folderPath & "\" & dirName) And vbDirectory Then
Debug.Print "Directory: " & dirName
End If
End If
dirName = Dir
Loop
End Sub</code></pre>
<h3 id="search-multiple-file-types">Search Multiple File Types</h3>
<pre><code class="language-vbnet">Function FindDocuments(folderPath As String) As Variant
Dim files() As String
Dim fileName As String
Dim count As Long
Dim extensions As Variant
Dim i As Integer
extensions = Array("*.txt", "*.doc", "*.docx", "*.pdf")
ReDim files(0 To 100)
count = 0
For i = LBound(extensions) To UBound(extensions)
fileName = Dir(folderPath & "\" & extensions(i))
Do While fileName <> ""
files(count) = fileName
count = count + 1
If count > UBound(files) Then
ReDim Preserve files(0 To UBound(files) + 100)
End If
fileName = Dir
Loop
Next i
If count > 0 Then
ReDim Preserve files(0 To count - 1)
FindDocuments = files
Else
FindDocuments = Array()
End If
End Function</code></pre>
<h3 id="get-full-file-paths">Get Full File Paths</h3>
<pre><code class="language-vbnet">Function GetFullPaths(folderPath As String, pattern As String) As Variant
Dim paths() As String
Dim fileName As String
Dim count As Long
count = 0
ReDim paths(0 To 100)
fileName = Dir(folderPath & "\" & pattern)
Do While fileName <> ""
paths(count) = folderPath & "\" & fileName
count = count + 1
If count > UBound(paths) Then
ReDim Preserve paths(0 To UBound(paths) + 100)
End If
fileName = Dir
Loop
If count > 0 Then
ReDim Preserve paths(0 To count - 1)
GetFullPaths = paths
Else
GetFullPaths = Array()
End If
End Function</code></pre>
<h3 id="delete-all-files-matching-pattern">Delete All Files Matching Pattern</h3>
<pre><code class="language-vbnet">Sub DeleteMatchingFiles(folderPath As String, pattern As String)
Dim fileName As String
Dim fullPath As String
fileName = Dir(folderPath & "\" & pattern)
Do While fileName <> ""
fullPath = folderPath & "\" & fileName
' Get next file BEFORE deleting (Dir state would be lost)
fileName = Dir
' Delete the file
Kill fullPath
Loop
End Sub</code></pre>
<h3 id="find-newest-file">Find Newest File</h3>
<pre><code class="language-vbnet">Function GetNewestFile(folderPath As String, pattern As String) As String
Dim fileName As String
Dim newestFile As String
Dim newestDate As Date
Dim currentDate As Date
Dim fullPath As String
newestDate = 0
fileName = Dir(folderPath & "\" & pattern)
Do While fileName <> ""
fullPath = folderPath & "\" & fileName
currentDate = FileDateTime(fullPath)
If currentDate > newestDate Then
newestDate = currentDate
newestFile = fileName
End If
fileName = Dir
Loop
GetNewestFile = newestFile
End Function</code></pre>
<h3 id="calculate-total-size">Calculate Total Size</h3>
<pre><code class="language-vbnet">Function GetTotalFileSize(folderPath As String, pattern As String) As Double
Dim fileName As String
Dim totalSize As Double
Dim fullPath As String
totalSize = 0
fileName = Dir(folderPath & "\" & pattern)
Do While fileName <> ""
fullPath = folderPath & "\" & fileName
totalSize = totalSize + FileLen(fullPath)
fileName = Dir
Loop
GetTotalFileSize = totalSize
End Function</code></pre>
<h3 id="recursive-directory-search">Recursive Directory Search</h3>
<pre><code class="language-vbnet">Sub SearchRecursive(folderPath As String, pattern As String)
Dim fileName As String
Dim dirName As String
Dim fullPath As String
' Search files in current directory
fileName = Dir(folderPath & "\" & pattern)
Do While fileName <> ""
Debug.Print folderPath & "\" & fileName
fileName = Dir
Loop
' Search subdirectories
dirName = Dir(folderPath & "\*.*", vbDirectory)
Do While dirName <> ""
If dirName <> "." And dirName <> ".." Then
fullPath = folderPath & "\" & dirName
If GetAttr(fullPath) And vbDirectory Then
SearchRecursive fullPath, pattern
End If
End If
dirName = Dir
Loop
End Sub</code></pre>
<h2 id="advanced-usage">Advanced Usage</h2>
<h3 id="file-filter-with-multiple-criteria">File Filter with Multiple Criteria</h3>
<pre><code class="language-vbnet">Function FindFilesAdvanced(folderPath As String, _
minSize As Long, maxSize As Long, _
afterDate As Date) As Variant
Dim files() As String
Dim fileName As String
Dim fullPath As String
Dim fileSize As Long
Dim fileDate As Date
Dim count As Long
count = 0
ReDim files(0 To 100)
fileName = Dir(folderPath & "\*.*")
Do While fileName <> ""
fullPath = folderPath & "\" & fileName
fileSize = FileLen(fullPath)
fileDate = FileDateTime(fullPath)
If fileSize >= minSize And fileSize <= maxSize And fileDate > afterDate Then
files(count) = fileName
count = count + 1
If count > UBound(files) Then
ReDim Preserve files(0 To UBound(files) + 100)
End If
End If
fileName = Dir
Loop
If count > 0 Then
ReDim Preserve files(0 To count - 1)
FindFilesAdvanced = files
Else
FindFilesAdvanced = Array()
End If
End Function</code></pre>
<h3 id="safe-dir-loop-helper">Safe Dir Loop Helper</h3>
<pre><code class="language-vbnet">' Helper to avoid nested Dir issues
Type FileInfo
Name As String
FullPath As String
Size As Long
Modified As Date
End Type
Function GetFileInfoList(folderPath As String, pattern As String) As Variant
Dim files() As FileInfo
Dim fileName As String
Dim count As Long
count = 0
ReDim files(0 To 100)
fileName = Dir(folderPath & "\" & pattern)
Do While fileName <> ""
files(count).Name = fileName
files(count).FullPath = folderPath & "\" & fileName
files(count).Size = FileLen(files(count).FullPath)
files(count).Modified = FileDateTime(files(count).FullPath)
count = count + 1
If count > UBound(files) Then
ReDim Preserve files(0 To UBound(files) + 100)
End If
fileName = Dir
Loop
If count > 0 Then
ReDim Preserve files(0 To count - 1)
GetFileInfoList = files
Else
GetFileInfoList = Array()
End If
End Function</code></pre>
<h3 id="backup-old-files">Backup Old Files</h3>
<pre><code class="language-vbnet">Sub BackupOldFiles(sourcePath As String, backupPath As String, daysOld As Integer)
Dim fileName As String
Dim fullPath As String
Dim cutoffDate As Date
cutoffDate = Date - daysOld
fileName = Dir(sourcePath & "\*.*")
Do While fileName <> ""
fullPath = sourcePath & "\" & fileName
If FileDateTime(fullPath) < cutoffDate Then
FileCopy fullPath, backupPath & "\" & fileName
End If
fileName = Dir
Loop
End Sub</code></pre>
<h3 id="build-file-index">Build File Index</h3>
<pre><code class="language-vbnet">Function BuildFileIndex(rootPath As String) As Collection
Dim index As New Collection
Dim fileName As String
' Add all files to collection with full path as key
fileName = Dir(rootPath & "\*.*")
Do While fileName <> ""
On Error Resume Next
index.Add fileName, UCase(fileName)
On Error GoTo 0
fileName = Dir
Loop
Set BuildFileIndex = index
End Function</code></pre>
<h3 id="file-synchronization-check">File Synchronization Check</h3>
<pre><code class="language-vbnet">Function CompareDirectories(path1 As String, path2 As String) As String
Dim files1 As Collection
Dim files2 As Collection
Dim fileName As String
Dim report As String
Set files1 = New Collection
Set files2 = New Collection
' Get files from first directory
fileName = Dir(path1 & "\*.*")
Do While fileName <> ""
files1.Add fileName
fileName = Dir
Loop
' Get files from second directory
fileName = Dir(path2 & "\*.*")
Do While fileName <> ""
files2.Add fileName
fileName = Dir
Loop
' Compare (simplified - full version would check both ways)
report = "Files only in " & path1 & ":" & vbCrLf
' ... comparison logic ...
CompareDirectories = report
End Function</code></pre>
<h3 id="generate-directory-listing-report">Generate Directory Listing Report</h3>
<pre><code class="language-vbnet">Sub ExportDirectoryListing(folderPath As String, outputFile As String)
Dim fileName As String
Dim fullPath As String
Dim fileNum As Integer
fileNum = FreeFile
Open outputFile For Output As #fileNum
Print #fileNum, "Directory Listing for: " & folderPath
Print #fileNum, "Generated: " & Now
Print #fileNum, String(80, "-")
Print #fileNum, "Filename" & vbTab & "Size" & vbTab & "Modified"
Print #fileNum, String(80, "-")
fileName = Dir(folderPath & "\*.*")
Do While fileName <> ""
fullPath = folderPath & "\" & fileName
Print #fileNum, fileName & vbTab & _
FileLen(fullPath) & vbTab & _
FileDateTime(fullPath)
fileName = Dir
Loop
Close #fileNum
End Sub</code></pre>
<h2 id="error-handling">Error Handling</h2>
<pre><code class="language-vbnet">Function SafeDir(pathname As String, Optional attributes As Integer = 0) As String
On Error Resume Next
SafeDir = Dir(pathname, attributes)
If Err.Number <> 0 Then
SafeDir = ""
End If
End Function
Function SafeFileExists(filePath As String) As Boolean
On Error Resume Next
SafeFileExists = (Len(Dir(filePath)) > 0)
If Err.Number <> 0 Then
SafeFileExists = False
End If
End Function</code></pre>
<h3 id="common-errors">Common Errors</h3>
<ul>
<li><strong>Error 52</strong> (Bad file name or number): Invalid pathname or pattern</li>
<li><strong>Error 76</strong> (Path not found): Directory does not exist</li>
<li><strong>Error 68</strong> (Device unavailable): Drive not ready or network path unavailable</li>
</ul>
<h2 id="performance-considerations">Performance Considerations</h2>
<ul>
<li><code>Dir</code> is relatively fast for simple file enumeration</li>
<li>For large directories, consider showing progress</li>
<li>Network paths can be slow; consider timeout handling</li>
<li>Avoid nested <code>Dir</code> loops (collect to array first)</li>
<li><code>FileSystemObject</code> may be faster for complex operations</li>
<li>Cache results if scanning same directory repeatedly</li>
</ul>
<h2 id="best-practices">Best Practices</h2>
<h3 id="always-check-for-empty-string">Always Check for Empty String</h3>
<pre><code class="language-vbnet">' Good - Check for no more files
fileName = Dir("*.txt")
Do While fileName <> ""
' Process file
fileName = Dir
Loop
' Avoid - May cause infinite loop
fileName = Dir("*.txt")
Do While Len(fileName) > 0 ' Less reliable
fileName = Dir
Loop</code></pre>
<h3 id="store-files-before-processing">Store Files Before Processing</h3>
<pre><code class="language-vbnet">' Good - Collect files first
Dim files() As String, i As Integer
ReDim files(0 To 100)
count = 0
fileName = Dir("*.txt")
Do While fileName <> ""
files(count) = fileName
count = count + 1
fileName = Dir
Loop
' Now process without Dir active
For i = 0 To count - 1
ProcessFile files(i)
Next i</code></pre>
<h3 id="use-absolute-paths">Use Absolute Paths</h3>
<pre><code class="language-vbnet">' Good - Explicit path
fileName = Dir("C:\Data\*.txt")
' Risky - Depends on current directory
fileName = Dir("*.txt")</code></pre>
<h3 id="handle-no-matches-gracefully">Handle No Matches Gracefully</h3>
<pre><code class="language-vbnet">fileName = Dir("*.xyz")
If fileName = "" Then
MsgBox "No matching files found"
Exit Sub
End If</code></pre>
<h2 id="comparison-with-other-methods">Comparison with Other Methods</h2>
<h3 id="dir-vs-filesystemobject"><code>Dir</code> vs <code>FileSystemObject</code></h3>
<pre><code class="language-vbnet">' Dir - Built-in, faster for simple cases
fileName = Dir("C:\Data\*.txt")
' FileSystemObject - More features, but requires reference
Dim fso As New FileSystemObject
Dim folder As Folder
Set folder = fso.GetFolder("C:\Data")
' ... more complex but more powerful</code></pre>
<h3 id="dir-vs-file-dialog"><code>Dir</code> vs <code>File Dialog</code></h3>
<pre><code class="language-vbnet">' Dir - Programmatic file discovery
fileName = Dir("*.txt")
' File Dialog - User selection
fileName = Application.GetOpenFilename("Text Files (*.txt), *.txt")</code></pre>
<h2 id="limitations">Limitations</h2>
<ul>
<li>Cannot nest Dir loops reliably (single internal state)</li>
<li>Does not return files in sorted order</li>
<li>Returns only file names, not full paths</li>
<li>No built-in recursion into subdirectories</li>
<li>Cannot filter by date, size, or other attributes directly</li>
<li>Changing current directory during enumeration causes issues</li>
<li>Limited attribute filtering compared to <code>FileSystemObject</code></li>
</ul>
<h2 id="related-functions">Related Functions</h2>
<ul>
<li><code>GetAttr</code>: Gets file attributes</li>
<li><code>SetAttr</code>: Sets file attributes</li>
<li><code>FileLen</code>: Returns file size</li>
<li><code>FileDateTime</code>: Returns file modification date/time</li>
<li><code>CurDir</code>: Returns current directory</li>
<li><code>ChDir</code>: Changes current directory</li>
<li><code>MkDir</code>: Creates directory</li>
<li><code>RmDir</code>: Removes directory</li>
<li><code>Kill</code>: Deletes file</li>
<li><code>FileCopy</code>: Copies file</li>
<li><code>Name</code>: Renames/moves file</li>
</ul>
</article>
<div style="margin-top: 3rem; padding-top: 2rem; border-top: 1px solid var(--border-color);">
<p>
<a href="index.html">← Back to File</a> |
<a href="../index.html">View all functions</a>
</p>
</div>
</main>
<footer>
<div class="container">
<p>© 2024-2026 VB6Parse Contributors. Licensed under the MIT License.</p>
</div>
</footer>
</body>
</html>