DirectoryInfo DirectoryInfo DirectoryInfo DirectoryInfo Class

定義

公開建立、移動和全面列舉目錄和子目錄的執行個體 (Instance) 方法。Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. 這個類別無法被繼承。This class cannot be inherited.

public ref class DirectoryInfo sealed : System::IO::FileSystemInfo
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class DirectoryInfo : System.IO.FileSystemInfo
type DirectoryInfo = class
    inherit FileSystemInfo
Public NotInheritable Class DirectoryInfo
Inherits FileSystemInfo
繼承
屬性

範例

下列範例示範一些主要成員的DirectoryInfo類別。The following example demonstrates some of the main members of the DirectoryInfo class.

using namespace System;
using namespace System::IO;
int main()
{
   
   // Specify the directories you want to manipulate.
   DirectoryInfo^ di = gcnew DirectoryInfo( "c:\\MyDir" );
   try
   {
      
      // Determine whether the directory exists.
      if ( di->Exists )
      {
         
         // Indicate that the directory already exists.
         Console::WriteLine( "That path exists already." );
         return 0;
      }
      
      // Try to create the directory.
      di->Create();
      Console::WriteLine( "The directory was created successfully." );
      
      // Delete the directory.
      di->Delete();
      Console::WriteLine( "The directory was deleted successfully." );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }

}

using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        // Specify the directories you want to manipulate.
        DirectoryInfo di = new DirectoryInfo(@"c:\MyDir");
        try 
        {
            // Determine whether the directory exists.
            if (di.Exists) 
            {
                // Indicate that the directory already exists.
                Console.WriteLine("That path exists already.");
                return;
            }

            // Try to create the directory.
            di.Create();
            Console.WriteLine("The directory was created successfully.");

            // Delete the directory.
            di.Delete();
            Console.WriteLine("The directory was deleted successfully.");

        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        } 
        finally {}
    }
}
Imports System
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        ' Specify the directories you want to manipulate.
        Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir")
        Try
            ' Determine whether the directory exists.
            If di.Exists Then
                ' Indicate that it already exists.
                Console.WriteLine("That path exists already.")
                Return
            End If

            ' Try to create the directory.
            di.Create()
            Console.WriteLine("The directory was created successfully.")

            ' Delete the directory.
            di.Delete()
            Console.WriteLine("The directory was deleted successfully.")

        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

下列範例示範如何複製目錄及其內容。The following example demonstrates how to copy a directory and its contents.

using System;
using System.IO;

class CopyDir
{
    public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
    {
        if (source.FullName.ToLower() == target.FullName.ToLower())
        {
            return;
        }

        // Check if the target directory exists, if not, create it.
        if (Directory.Exists(target.FullName) == false)
        {
            Directory.CreateDirectory(target.FullName);
        }

        // Copy each file into it's new directory.
        foreach (FileInfo fi in source.GetFiles())
        {
            Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
            fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
        }

        // Copy each subdirectory using recursion.
        foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
        {
            DirectoryInfo nextTargetSubDir =
                target.CreateSubdirectory(diSourceSubDir.Name);
            CopyAll(diSourceSubDir, nextTargetSubDir);
        }
    }

    public static void Main()
    {
        string sourceDirectory = @"c:\sourceDirectory";
        string targetDirectory = @"c:\targetDirectory";

        DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
        DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);

        CopyAll(diSource, diTarget);
    }

    // Output will vary based on the contents of the source directory.
}
Imports System
Imports System.IO

Class CopyDir
    Shared Sub CopyAll(ByVal source As DirectoryInfo, ByVal target As DirectoryInfo)
        If (source.FullName.ToLower() = target.FullName.ToLower()) Then
            Return
        End If

        ' Check if the target directory exists, if not, create it.
        If Directory.Exists(target.FullName) = False Then
            Directory.CreateDirectory(target.FullName)
        End If

        ' Copy each file into it's new directory.
        For Each fi As FileInfo In source.GetFiles()
            Console.WriteLine("Copying {0}\{1}", target.FullName, fi.Name)
            fi.CopyTo(Path.Combine(target.ToString(), fi.Name), True)
        Next

        ' Copy each subdirectory using recursion.
        For Each diSourceSubDir As DirectoryInfo In source.GetDirectories()
            Dim nextTargetSubDir As DirectoryInfo = target.CreateSubdirectory(diSourceSubDir.Name)
            CopyAll(diSourceSubDir, nextTargetSubDir)
        Next
    End Sub

    Shared Sub Main()
        Dim sourceDirectory As String = "c:\\sourceDirectory"
        Dim targetDirectory As String = "c:\\targetDirectory"

        Dim diSource As DirectoryInfo = New DirectoryInfo(sourceDirectory)
        Dim diTarget As DirectoryInfo = New DirectoryInfo(targetDirectory)

        CopyAll(diSource, diTarget)
    End Sub
    ' Output will vary based on the contents of the source directory.
End Class

備註

使用DirectoryInfo類別,例如複製、 移動、 重新命名、 建立和刪除目錄的一般作業。Use the DirectoryInfo class for typical operations such as copying, moving, renaming, creating, and deleting directories.

如果您要重複使用的物件數次,請考慮使用的執行個體方法DirectoryInfo而非對應的靜態方法的Directory類別,因為安全性檢查不一定是必要的。If you are going to reuse an object several times, consider using the instance method of DirectoryInfo instead of the corresponding static methods of the Directory class, because a security check will not always be necessary.

注意

接受的路徑做為輸入字串的成員,該路徑必須是語式正確,或引發例外狀況。In members that accept a path as an input string, that path must be well-formed or an exception is raised. 比方說,如果路徑是完整名稱,但以空格開頭,路徑不被修剪中類別的方法。For example, if a path is fully qualified but begins with a space, the path is not trimmed in methods of the class. 因此,路徑的格式不正確,而且會引發例外狀況。Therefore, the path is malformed and an exception is raised. 同樣地,路徑的組合無法完整限定兩次。Similarly, a path or a combination of paths cannot be fully qualified twice. 例如,"c:\temp c:\windows,"也會引發例外狀況在大部分情況下。For example, "c:\temp c:\windows" also raises an exception in most cases. 請確定您的路徑是語式正確的當您使用接受路徑字串的方法。Ensure that your paths are well-formed when using methods that accept a path string.

在接受路徑的成員,路徑可以參考到檔案或只是一個目錄。In members that accept a path, the path can refer to a file or just a directory. 指定的路徑也可以參考相對路徑或通用命名慣例 (UNC) 路徑的伺服器和共用的名稱。The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. 例如,如果以下所有狀況可接受的路徑:For example, all the following are acceptable paths:

  • "c:\\MyDir\\MyFile.txt 」 以 C# 或 Visual Basic 中的 「 c:\MyDir\MyFile.txt"。"c:\\MyDir\\MyFile.txt" in C#, or "c:\MyDir\MyFile.txt" in Visual Basic.

  • "c:\\MyDir 」 以 C# 或 Visual Basic 中的 「 c:\mydir"。"c:\\MyDir" in C#, or "c:\MyDir" in Visual Basic.

  • "MyDir\\MySubdir 」 以 C# 或 Visual Basic 中的 「 MyDir\MySubDir"。"MyDir\\MySubdir" in C#, or "MyDir\MySubDir" in Visual Basic.

  • 「\\\\MyServer\\MyShare 」 在 C# 中,或 「\\MyServer\MyShare"在 Visual Basic 中。"\\\\MyServer\\MyShare" in C#, or "\\MyServer\MyShare" in Visual Basic.

根據預設,新的目錄完整讀取/寫入存取會授與所有使用者。By default, full read/write access to new directories is granted to all users.

如需一般 I/O 工作的清單,請參閱 < 一般 I/O 工作For a list of common I/O tasks, see Common I/O Tasks.

建構函式

DirectoryInfo(String) DirectoryInfo(String) DirectoryInfo(String) DirectoryInfo(String)

在指定的路徑上,初始化 DirectoryInfo 類別的新執行個體。Initializes a new instance of the DirectoryInfo class on the specified path.

屬性

Attributes Attributes Attributes Attributes

取得或設定目前檔案或目錄的屬性。Gets or sets the attributes for the current file or directory.

(Inherited from FileSystemInfo)
CreationTime CreationTime CreationTime CreationTime

取得或設定目前檔案或目錄的建立時間。Gets or sets the creation time of the current file or directory.

(Inherited from FileSystemInfo)
CreationTimeUtc CreationTimeUtc CreationTimeUtc CreationTimeUtc

取得或設定目前檔案或目錄的建立時間,其格式為國際標準時間 (Coordinated Universal Time,UTC)。Gets or sets the creation time, in coordinated universal time (UTC), of the current file or directory.

(Inherited from FileSystemInfo)
Exists Exists Exists Exists

取得值,指出目錄是否存在。Gets a value indicating whether the directory exists.

Extension Extension Extension Extension

取得字串,表示檔案的副檔名部分。Gets the string representing the extension part of the file.

(Inherited from FileSystemInfo)
FullName FullName FullName FullName

取得目錄的完整路徑。Gets the full path of the directory.

LastAccessTime LastAccessTime LastAccessTime LastAccessTime

取得或設定上次存取目前檔案或目錄的時間。Gets or sets the time the current file or directory was last accessed.

(Inherited from FileSystemInfo)
LastAccessTimeUtc LastAccessTimeUtc LastAccessTimeUtc LastAccessTimeUtc

取得或設定目前檔案或目錄上次被存取的時間,其格式為 Coordinated Universal Time (UTC)。Gets or sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed.

(Inherited from FileSystemInfo)
LastWriteTime LastWriteTime LastWriteTime LastWriteTime

取得或設定上次寫入目前檔案或目錄的時間。Gets or sets the time when the current file or directory was last written to.

(Inherited from FileSystemInfo)
LastWriteTimeUtc LastWriteTimeUtc LastWriteTimeUtc LastWriteTimeUtc

取得或設定目前檔案或目錄上次被寫入的時間,其格式為 Coordinated Universal Time (UTC)。Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to.

(Inherited from FileSystemInfo)
Name Name Name Name

取得這個 DirectoryInfo 執行個體的名稱。Gets the name of this DirectoryInfo instance.

Parent Parent Parent Parent

取得指定子目錄的父代 (Parent) 目錄。Gets the parent directory of a specified subdirectory.

Root Root Root Root

取得目錄的根目錄部分。Gets the root portion of the directory.

方法

Create() Create() Create() Create()

建立目錄。Creates a directory.

Create(DirectorySecurity) Create(DirectorySecurity) Create(DirectorySecurity) Create(DirectorySecurity)

使用 DirectorySecurity 物件建立目錄Creates a directory using a DirectorySecurity object.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateSubdirectory(String) CreateSubdirectory(String) CreateSubdirectory(String) CreateSubdirectory(String)

在指定路徑上建立子目錄。Creates a subdirectory or subdirectories on the specified path. 指定的路徑可以相對於 DirectoryInfo 類別的這個執行個體。The specified path can be relative to this instance of the DirectoryInfo class.

CreateSubdirectory(String, DirectorySecurity) CreateSubdirectory(String, DirectorySecurity) CreateSubdirectory(String, DirectorySecurity) CreateSubdirectory(String, DirectorySecurity)

使用指定的安全性在指定路徑上建立子目錄。Creates a subdirectory or subdirectories on the specified path with the specified security. 指定的路徑可以相對於 DirectoryInfo 類別的這個執行個體。The specified path can be relative to this instance of the DirectoryInfo class.

Delete() Delete() Delete() Delete()

如果這個 DirectoryInfo 是空的,則將它刪除。Deletes this DirectoryInfo if it is empty.

Delete(Boolean) Delete(Boolean) Delete(Boolean) Delete(Boolean)

刪除 DirectoryInfo 的這個執行個體,指定是否刪除子目錄和檔案。Deletes this instance of a DirectoryInfo, specifying whether to delete subdirectories and files.

EnumerateDirectories() EnumerateDirectories() EnumerateDirectories() EnumerateDirectories()

傳回目前目錄中目錄資訊的可列舉集合。Returns an enumerable collection of directory information in the current directory.

EnumerateDirectories(String) EnumerateDirectories(String) EnumerateDirectories(String) EnumerateDirectories(String)

傳回符合指定之搜尋模式的目錄資訊的可列舉集合。Returns an enumerable collection of directory information that matches a specified search pattern.

EnumerateDirectories(String, EnumerationOptions) EnumerateDirectories(String, EnumerationOptions) EnumerateDirectories(String, EnumerationOptions) EnumerateDirectories(String, EnumerationOptions)
EnumerateDirectories(String, SearchOption) EnumerateDirectories(String, SearchOption) EnumerateDirectories(String, SearchOption) EnumerateDirectories(String, SearchOption)

傳回符合指定之搜尋模式和搜尋子目錄選項的目錄資訊的可列舉集合。Returns an enumerable collection of directory information that matches a specified search pattern and search subdirectory option.

EnumerateFiles() EnumerateFiles() EnumerateFiles() EnumerateFiles()

傳回目前目錄中檔案資訊的可列舉集合。Returns an enumerable collection of file information in the current directory.

EnumerateFiles(String) EnumerateFiles(String) EnumerateFiles(String) EnumerateFiles(String)

傳回符合指定之搜尋模式的檔案資訊的可列舉集合。Returns an enumerable collection of file information that matches a search pattern.

EnumerateFiles(String, EnumerationOptions) EnumerateFiles(String, EnumerationOptions) EnumerateFiles(String, EnumerationOptions) EnumerateFiles(String, EnumerationOptions)
EnumerateFiles(String, SearchOption) EnumerateFiles(String, SearchOption) EnumerateFiles(String, SearchOption) EnumerateFiles(String, SearchOption)

傳回符合指定之搜尋模式和搜尋子目錄選項的檔案資訊的可列舉集合。Returns an enumerable collection of file information that matches a specified search pattern and search subdirectory option.

EnumerateFileSystemInfos() EnumerateFileSystemInfos() EnumerateFileSystemInfos() EnumerateFileSystemInfos()

傳回目前目錄中檔案系統資訊的可列舉集合。Returns an enumerable collection of file system information in the current directory.

EnumerateFileSystemInfos(String) EnumerateFileSystemInfos(String) EnumerateFileSystemInfos(String) EnumerateFileSystemInfos(String)

傳回符合指定之搜尋模式的檔案系統資訊的可列舉集合。Returns an enumerable collection of file system information that matches a specified search pattern.

EnumerateFileSystemInfos(String, EnumerationOptions) EnumerateFileSystemInfos(String, EnumerationOptions) EnumerateFileSystemInfos(String, EnumerationOptions) EnumerateFileSystemInfos(String, EnumerationOptions)
EnumerateFileSystemInfos(String, SearchOption) EnumerateFileSystemInfos(String, SearchOption) EnumerateFileSystemInfos(String, SearchOption) EnumerateFileSystemInfos(String, SearchOption)

傳回符合指定之搜尋模式和搜尋子目錄選項的檔案系統資訊的可列舉集合。Returns an enumerable collection of file system information that matches a specified search pattern and search subdirectory option.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetAccessControl() GetAccessControl() GetAccessControl() GetAccessControl()

取得 DirectorySecurity 物件,該物件會封裝由目前 DirectoryInfo 物件所描述之目錄的存取控制清單 (ACL) 項目。Gets a DirectorySecurity object that encapsulates the access control list (ACL) entries for the directory described by the current DirectoryInfo object.

GetAccessControl(AccessControlSections) GetAccessControl(AccessControlSections) GetAccessControl(AccessControlSections) GetAccessControl(AccessControlSections)

取得 DirectorySecurity 物件,該物件會封裝由目前 DirectoryInfo 物件所描述之目錄的指定型別存取控制清單 (ACL) 項目。Gets a DirectorySecurity object that encapsulates the specified type of access control list (ACL) entries for the directory described by the current DirectoryInfo object.

GetDirectories() GetDirectories() GetDirectories() GetDirectories()

傳回目前目錄的子目錄。Returns the subdirectories of the current directory.

GetDirectories(String) GetDirectories(String) GetDirectories(String) GetDirectories(String)

傳回在目前 DirectoryInfo 中,符合指定的搜尋準則的目錄陣列。Returns an array of directories in the current DirectoryInfo matching the given search criteria.

GetDirectories(String, EnumerationOptions) GetDirectories(String, EnumerationOptions) GetDirectories(String, EnumerationOptions) GetDirectories(String, EnumerationOptions)
GetDirectories(String, SearchOption) GetDirectories(String, SearchOption) GetDirectories(String, SearchOption) GetDirectories(String, SearchOption)

傳回目前 DirectoryInfo 中的目錄陣列,這些目錄符合指定的搜尋準則並使用值來判斷是否搜尋子目錄。Returns an array of directories in the current DirectoryInfo matching the given search criteria and using a value to determine whether to search subdirectories.

GetFiles() GetFiles() GetFiles() GetFiles()

從目前的目錄傳回檔案清單。Returns a file list from the current directory.

GetFiles(String) GetFiles(String) GetFiles(String) GetFiles(String)

從目前目錄傳回符合指定之搜尋模式的檔案清單。Returns a file list from the current directory matching the given search pattern.

GetFiles(String, EnumerationOptions) GetFiles(String, EnumerationOptions) GetFiles(String, EnumerationOptions) GetFiles(String, EnumerationOptions)
GetFiles(String, SearchOption) GetFiles(String, SearchOption) GetFiles(String, SearchOption) GetFiles(String, SearchOption)

從目前目錄傳回符合指定搜尋模式的檔案清單,並使用值來判斷是否搜尋子目錄。Returns a file list from the current directory matching the given search pattern and using a value to determine whether to search subdirectories.

GetFileSystemInfos() GetFileSystemInfos() GetFileSystemInfos() GetFileSystemInfos()

傳回強型別 FileSystemInfo 項目的陣列,表示目錄中的所有檔案和子目錄。Returns an array of strongly typed FileSystemInfo entries representing all the files and subdirectories in a directory.

GetFileSystemInfos(String) GetFileSystemInfos(String) GetFileSystemInfos(String) GetFileSystemInfos(String)

擷取強型別 FileSystemInfo 物件的陣列,表示符合指定之搜尋準則的檔案和子目錄。Retrieves an array of strongly typed FileSystemInfo objects representing the files and subdirectories that match the specified search criteria.

GetFileSystemInfos(String, EnumerationOptions) GetFileSystemInfos(String, EnumerationOptions) GetFileSystemInfos(String, EnumerationOptions) GetFileSystemInfos(String, EnumerationOptions)
GetFileSystemInfos(String, SearchOption) GetFileSystemInfos(String, SearchOption) GetFileSystemInfos(String, SearchOption) GetFileSystemInfos(String, SearchOption)

擷取 FileSystemInfo 物件的陣列,表示符合指定之搜尋準則的檔案和子目錄。Retrieves an array of FileSystemInfo objects that represent the files and subdirectories matching the specified search criteria.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

以檔案名稱和其他例外狀況資訊設定 SerializationInfo 物件。Sets the SerializationInfo object with the file name and additional exception information.

(Inherited from FileSystemInfo)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
MoveTo(String) MoveTo(String) MoveTo(String) MoveTo(String)

移動 DirectoryInfo 執行個體和其內容至新的路徑。Moves a DirectoryInfo instance and its contents to a new path.

Refresh() Refresh() Refresh() Refresh()

重新整理物件的狀態。Refreshes the state of the object.

(Inherited from FileSystemInfo)
SetAccessControl(DirectorySecurity) SetAccessControl(DirectorySecurity) SetAccessControl(DirectorySecurity) SetAccessControl(DirectorySecurity)

DirectorySecurity 物件所描述的存取控制清單 (ACL) 項目套用至目前 DirectoryInfo 物件所描述的目錄。Applies access control list (ACL) entries described by a DirectorySecurity object to the directory described by the current DirectoryInfo object.

ToString() ToString() ToString() ToString()

傳回已由使用者傳遞的原始路徑。Returns the original path that was passed by the user.

欄位

FullPath FullPath FullPath FullPath

表示目錄或檔案的完整路徑。Represents the fully qualified path of the directory or file.

(Inherited from FileSystemInfo)
OriginalPath OriginalPath OriginalPath OriginalPath

使用者指定的相對或絕對的原始路徑。The path originally specified by the user, whether relative or absolute.

(Inherited from FileSystemInfo)

擴充方法

GetAccessControl(DirectoryInfo) GetAccessControl(DirectoryInfo) GetAccessControl(DirectoryInfo) GetAccessControl(DirectoryInfo)
GetAccessControl(DirectoryInfo, AccessControlSections) GetAccessControl(DirectoryInfo, AccessControlSections) GetAccessControl(DirectoryInfo, AccessControlSections) GetAccessControl(DirectoryInfo, AccessControlSections)
SetAccessControl(DirectoryInfo, DirectorySecurity) SetAccessControl(DirectoryInfo, DirectorySecurity) SetAccessControl(DirectoryInfo, DirectorySecurity) SetAccessControl(DirectoryInfo, DirectorySecurity)

適用於

另請參閱