共用方式為


Dir 函式

更新:2007 年 11 月

傳回的字串表示符合指定模式或檔案屬性 (Attribute) 的檔案、目錄或資料夾的名稱,也可以是磁碟機的磁碟區標籤 (Label)。

My.Computer.FileSystem 物件 在檔案 I/O 作業中的產能和效能勝過 Dir 功能。如需詳細資訊,請參閱 My.Computer.FileSystem.GetDirectoryInfo 方法

 Public Overloads Function Dir() As String ' -or- Public Overloads Function Dir( _        ByVal PathName As String, _         Optional ByVal Attributes As FileAttribute = FileAttribute.Normal _ ) As String

參數

  • PathName
    選擇項。指定檔案名稱、目錄或資料夾名稱或是磁碟機磁碟區標籤的 String 運算式。如果找不到 PathName,則會傳回長度為零的字串 ("")。

  • Attributes
    選擇項。列舉或數值運算式 (Numeric Expression),其值指定檔案屬性 (Attribute)。如果省略,Dir 則會傳回符合 PathName 但沒有屬性的檔案。

設定

Attributes 引數列舉值如下:

常數

描述

Normal

vbnormal

預設值。指定不含任何屬性的檔案。

ReadOnly

vbReadOnly

除了不含任何屬性的檔案之外,也指定唯讀檔案。

Hidden

vbHidden

除了不含任何屬性的檔案之外,也指定隱藏檔案。

System

vbSystem

除了不含任何屬性的檔案之外,也指定系統檔案。

Volume

vbVolume

指定磁碟區標籤,若已指定任何其他屬性,則會忽略 vbVolume。

Directory

vbDirectory

除了不含任何屬性的檔案之外,也指定目錄或資料夾。

Archive

vbArchive

檔案自上次備份後已經過修改。

Alias

vbAlias

檔案具有不同的名稱。

注意事項:

這些列舉型別是由 Visual Basic 語言所指定,而且在程式碼中的任何地方使用,以取代實際值。

備註

Dir 函式可支援使用多字元 (*) 和單一字元 (?) 萬用字元來指定多個檔案。

VbVolume 傳回磁碟的磁碟區標籤,而不是特定檔案名稱。

第一次呼叫 Dir 函式時,必須提供 PathName。若要擷取下一個項目,您可以對沒有參數的 Dir 函式進行後續呼叫。

安全性注意事項:

若要正確執行,Dir 函式要求必須將 FileIOPermissionReadPathDiscovery 旗標授與執行程式碼。如需詳細資訊,請參閱 FileIOPermissionSecurityException程式碼存取使用權限

範例

這個範例會使用 Dir 函式,來檢查特定檔案和目錄是否存在。

Dim MyFile, MyPath, MyName As String
' Returns "WIN.INI" if it exists.
MyFile = Dir("C:\WINDOWS\WIN.INI")   

' Returns filename with specified extension. If more than one *.INI
' file exists, the first file found is returned.
MyFile = Dir("C:\WINDOWS\*.INI")

' Call Dir again without arguments to return the next *.INI file in the
' same directory.
MyFile = Dir()

' Return first *.TXT file, including files with a set hidden attribute.
MyFile = Dir("*.TXT", vbHidden)

' Display the names in C:\ that represent directories.
MyPath = "c:\"   ' Set the path.
MyName = Dir(MyPath, vbDirectory)   ' Retrieve the first entry.
Do While MyName <> ""   ' Start the loop.
      ' Use bitwise comparison to make sure MyName is a directory.
      If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then
         ' Display entry only if it's a directory.
         MsgBox(MyName)
      End If   
   MyName = Dir()   ' Get next entry.
Loop

智慧型裝置開發人員注意事項

不支援這個函式。

需求

命名空間 (Namespace)︰Microsoft.VisualBasic

**模組︰**FileSystem

組件 (Assembly):Visual Basic Runtime Library (在 Microsoft.VisualBasic.dll 中)

請參閱

參考

ChDir 函式

CurDir 函式

FileAttribute 列舉型別