DirectoryInfo 類別

定義

公開建立、移動和全面列舉目錄和子目錄的執行個體 (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.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.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#Visual Basic 中的 "c:\\MyDir\\MyFile.txt" 或 "c:\MyDir\MyFile.txt"。"c:\\MyDir\\MyFile.txt" in C#, or "c:\MyDir\MyFile.txt" in Visual Basic.

  • 中C#的 "c:\\MyDir",或 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#,或\中的「Visual Basic \myserver\myshare 則」。"\\\\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 類別的新執行個體。Initializes a new instance of the DirectoryInfo class on the specified path.

欄位

FullPath

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

(繼承來源 FileSystemInfo)
OriginalPath

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

(繼承來源 FileSystemInfo)

屬性

Attributes

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

(繼承來源 FileSystemInfo)
CreationTime

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

(繼承來源 FileSystemInfo)
CreationTimeUtc

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

(繼承來源 FileSystemInfo)
Exists

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

Extension

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

(繼承來源 FileSystemInfo)
FullName

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

LastAccessTime

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

(繼承來源 FileSystemInfo)
LastAccessTimeUtc

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

(繼承來源 FileSystemInfo)
LastWriteTime

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

(繼承來源 FileSystemInfo)
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.

(繼承來源 FileSystemInfo)
Name

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

Parent

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

Root

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

方法

Create()

建立目錄。Creates a directory.

Create(DirectorySecurity)

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

CreateObjRef(Type)

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

(繼承來源 MarshalByRefObject)
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)

使用指定的安全性在指定路徑上建立子目錄。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()

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

Delete(Boolean)

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

EnumerateDirectories()

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

EnumerateDirectories(String)

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

EnumerateDirectories(String, EnumerationOptions)

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

EnumerateDirectories(String, SearchOption)

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

EnumerateFiles()

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

EnumerateFiles(String)

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

EnumerateFiles(String, EnumerationOptions)

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

EnumerateFiles(String, SearchOption)

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

EnumerateFileSystemInfos()

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

EnumerateFileSystemInfos(String)

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

EnumerateFileSystemInfos(String, EnumerationOptions)

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

EnumerateFileSystemInfos(String, SearchOption)

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

Equals(Object)

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

(繼承來源 Object)
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)

取得 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()

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

GetDirectories(String)

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

GetDirectories(String, EnumerationOptions)

傳回目前 DirectoryInfo 中符合指定搜尋模式和列舉選項的目錄陣列。Returns an array of directories in the current DirectoryInfo matching the specified search pattern and enumeration options.

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()

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

GetFiles(String)

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

GetFiles(String, EnumerationOptions)

傳回目前目錄中符合指定搜尋模式和列舉選項的檔案清單。Returns a file list from the current directory matching the specified search pattern and enumeration options.

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()

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

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)

擷取代表符合指定搜尋模式和列舉選項之檔案和子目錄的強型別 FileSystemInfo 物件陣列。Retrieves an array of strongly typed FileSystemInfo objects representing the files and subdirectories that match the specified search pattern and enumeration options.

GetFileSystemInfos(String, SearchOption)

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

GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetLifetimeService()

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

(繼承來源 MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)

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

(繼承來源 FileSystemInfo)
GetType()

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

(繼承來源 Object)
InitializeLifetimeService()

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

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
MemberwiseClone(Boolean)

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

(繼承來源 MarshalByRefObject)
MoveTo(String)

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

Refresh()

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

(繼承來源 FileSystemInfo)
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()

傳回傳遞給 DirectoryInfo 建構函式的原始路徑。Returns the original path that was passed to the DirectoryInfo constructor. 使用 FullNameName 屬性作為完整路徑或檔案/目錄名稱,而不要使用這個方法。Use the FullName or Name properties for the full path or file/directory name instead of this method.

擴充方法

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

適用於

另請參閱