Directory Directory Directory Directory Class

定義

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

public ref class Directory abstract sealed
[System.Runtime.InteropServices.ComVisible(true)]
public static class Directory
type Directory = class
Public Class Directory
繼承
DirectoryDirectoryDirectoryDirectory
屬性

範例

下列範例示範如何從目錄擷取所有文字檔案,並將其移至新的目錄。The following example shows how to retrieve all the text files from a directory and move them to a new directory. 不會移動檔案之後,它們不再存在於原始的目錄。After the files are moved, they no longer exist in the original directory.

using System;
using System.IO;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourceDirectory = @"C:\current";
            string archiveDirectory = @"C:\archive";

            try
            {
                var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt");

                foreach (string currentFile in txtFiles)
                {
                    string fileName = currentFile.Substring(sourceDirectory.Length + 1);
                    Directory.Move(currentFile, Path.Combine(archiveDirectory, fileName));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
Imports System.IO

Module Module1

    Sub Main()
        Dim sourceDirectory As String = "C:\current"
        Dim archiveDirectory As String = "C:\archive"

        Try
            Dim txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt")

            For Each currentFile As String In txtFiles
                Dim fileName = currentFile.Substring(sourceDirectory.Length + 1)
                Directory.Move(currentFile, Path.Combine(archiveDirectory, fileName))
            Next
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try
    End Sub

End Module

下列範例示範如何使用EnumerateFiles方法從目錄中,擷取一組文字檔案,並接著在查詢中使用該集合,來尋找包含"Example"的所有行。The following example demonstrates how to use the EnumerateFiles method to retrieve a collection of text files from a directory, and then use that collection in a query to find all the lines that contain "Example".

using System;
using System.IO;
using System.Linq;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string archiveDirectory = @"C:\archive";

            var files = from retrievedFile in Directory.EnumerateFiles(archiveDirectory, "*.txt", SearchOption.AllDirectories)
                        from line in File.ReadLines(retrievedFile)
                        where line.Contains("Example")
                        select new
                        {
                            File = retrievedFile,
                            Line = line
                        };

            foreach (var f in files)
            {
                Console.WriteLine("{0} contains {1}", f.File, f.Line);
            }
            Console.WriteLine("{0} lines found.", files.Count().ToString());
        }
    }
}
Imports System.IO

Module Module1

    Sub Main()
        Dim archiveDirectory As String = "C:\archive"

        Dim files = From retrievedFile In Directory.EnumerateFiles(archiveDirectory, "*.txt", SearchOption.AllDirectories)
                    From line In File.ReadLines(retrievedFile)
                    Where line.Contains("Example")
                    Select New With {.curFile = retrievedFile, .curLine = line}

        For Each f In files
            Console.WriteLine("{0} contains {1}", f.curFile, f.curLine)
        Next
        Console.WriteLine("{0} lines found.", files.Count.ToString())

    End Sub

End Module

下列範例示範如何將目錄和其所有的檔案移至新的目錄。The following example demonstrates how to move a directory and all its files to a new directory. 已移動之後,原始的目錄不存在。The original directory no longer exists after it has been moved.

using System;
using System.IO;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourceDirectory = @"C:\source";
            string destinationDirectory = @"C:\destination";

            try
            {
                Directory.Move(sourceDirectory, destinationDirectory);  
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
Imports System.IO

Module Module1

    Sub Main()
        Dim sourceDirectory As String = "C:\source"
        Dim destinationDirectory As String = "C:\destination"

        Try
            Directory.Move(sourceDirectory, destinationDirectory)
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try

    End Sub

End Module

備註

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

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

如果您正在執行只有一個目錄相關的動作,它可能更有效率使用靜態Directory方法,而不是對應DirectoryInfo執行個體方法。If you are performing only one directory-related action, it might be more efficient to use a static Directory method rather than a corresponding DirectoryInfo instance method. 大部分Directory方法需要您操作的目錄路徑。Most Directory methods require the path to the directory that you are manipulating.

注意

在接受字串的成員中path參數,該路徑必須是語式正確,或引發例外狀況。In members that accept a string path parameter, that path must be well-formed or an exception is raised. 比方說,如果路徑是完整名稱,但開頭是空格 ("c:\temp"),路徑字串未修剪,因此路徑會被視為格式不正確,並引發例外狀況。For example, if a path is fully qualified but begins with a space (" c:\temp"), the path string isn't trimmed, so the path is considered malformed and an exception is raised. 此外,路徑的組合無法完整限定兩次。In addition, 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. 請確定您的路徑是語式正確的當您使用接受路徑字串的方法。Ensure that your paths are well-formed when using methods that accept a path string. 如需詳細資訊,請參閱PathFor more information see Path.

在接受路徑的成員,路徑可以參考到檔案或目錄。In members that accept a path, the path can refer to a file or a directory. 您可以使用完整的路徑、 相對路徑或通用命名慣例 (UNC) 路徑的伺服器和共用的名稱。You can use a full path, 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 」 以 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. 不過,應用程式必須有正確的安全性來存取現有的目錄。However, the app must have the correct security to access existing directories.

若要要求權限的目錄和所有其子目錄,最後目錄分隔符號字元的路徑字串。To demand permissions for a directory and all its subdirectories, end the path string with the directory separator character. (例如,"C:\Temp\」 會授與 C:\Temp\ 及其所有子目錄的存取。)若要只針對特定的目錄路徑字串,以句點結束的要求權限。(For example, "C:\Temp\" grants access to C:\Temp\ and all its subdirectories.) To demand permissions only for a specific directory, end the path string with a period. (例如,"C:\Temp\。 」(For example, "C:\Temp\." 僅授權存取至 C:\Temp\,而非其子目錄。)grants access only to C:\Temp\, not to its subdirectories.)

在 接受的成員searchPattern參數,搜尋字串可以是常值字元和兩個萬用字元; 的任何組合*和?。In members that accept a searchPattern parameter, the search string can be any combination of literal characters and two wildcard characters; * and ?. 這個參數無法辨識的規則運算式。This parameter does not recognize regular expressions. 如需詳細資訊,請參閱 < EnumerateDirectories(String, String) 方法或任何其他方法,會使用searchPattern參數。For more information, see the EnumerateDirectories(String, String) method or any other method that uses the searchPattern parameter.

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

DirectoryDirectoryInfo不支援用於Windows 市集Windows Store應用程式。Directory and DirectoryInfo are not supported for use in Windows 市集Windows Store apps. 如需如何存取檔案和資料夾Windows 市集Windows Store應用程式,請參閱存取資料和檔案 (Windows 市集應用程式)For information about how to access files and folders in Windows 市集Windows Store apps, see Accessing data and files (Windows Store apps).

方法

CreateDirectory(String) CreateDirectory(String) CreateDirectory(String) CreateDirectory(String)

在指定的路徑建立所有目錄和子目錄 (如果這些目錄尚不存在)。Creates all directories and subdirectories in the specified path unless they already exist.

CreateDirectory(String, DirectorySecurity) CreateDirectory(String, DirectorySecurity) CreateDirectory(String, DirectorySecurity) CreateDirectory(String, DirectorySecurity)

在指定的路徑中建立所有目錄 (如果尚不存在),同時套用指定的 Windows 安全性。Creates all the directories in the specified path, unless the already exist, applying the specified Windows security.

Delete(String) Delete(String) Delete(String) Delete(String)

從指定的路徑刪除空目錄。Deletes an empty directory from a specified path.

Delete(String, Boolean) Delete(String, Boolean) Delete(String, Boolean) Delete(String, Boolean)

刪除指定目錄,並且若有指示,則刪除目錄中的任何子目錄和檔案。Deletes the specified directory and, if indicated, any subdirectories and files in the directory.

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

傳回指定之路徑中目錄名稱的可列舉集合。Returns an enumerable collection of directory names in a specified path.

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

傳回指定之路徑中符合搜尋模式之目錄名稱的可列舉集合。Returns an enumerable collection of directory names that match a search pattern in a specified path.

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

傳回指定之路徑中符合搜尋模式之目錄名稱的可列舉集合,並選擇性地搜尋子目錄。Returns an enumerable collection of directory names that match a search pattern in a specified path, and optionally searches subdirectories.

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

傳回指定之路徑中符合搜尋模式之檔名的可列舉集合,並選擇性地搜尋子目錄。Returns an enumerable collection of file names that match a search pattern in a specified path, and optionally searches subdirectories.

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

傳回指定之路徑中檔案名稱的可列舉集合。Returns an enumerable collection of file names in a specified path.

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

傳回指定之路徑中符合搜尋模式之檔名的可列舉集合。Returns an enumerable collection of file names that match a search pattern in a specified path.

EnumerateFileSystemEntries(String) EnumerateFileSystemEntries(String) EnumerateFileSystemEntries(String) EnumerateFileSystemEntries(String)

傳回指定之路徑中檔案名稱及目錄名稱的可列舉集合。Returns an enumerable collection of file names and directory names in a specified path.

EnumerateFileSystemEntries(String, String) EnumerateFileSystemEntries(String, String) EnumerateFileSystemEntries(String, String) EnumerateFileSystemEntries(String, String)

傳回指定之路徑中符合搜尋模式之檔案名稱及目錄名稱的可列舉集合。Returns an enumerable collection of file names and directory names that match a search pattern in a specified path.

EnumerateFileSystemEntries(String, String, EnumerationOptions) EnumerateFileSystemEntries(String, String, EnumerationOptions) EnumerateFileSystemEntries(String, String, EnumerationOptions) EnumerateFileSystemEntries(String, String, EnumerationOptions)
EnumerateFileSystemEntries(String, String, SearchOption) EnumerateFileSystemEntries(String, String, SearchOption) EnumerateFileSystemEntries(String, String, SearchOption) EnumerateFileSystemEntries(String, String, SearchOption)

傳回指定之路徑中符合搜尋模式之檔名和目錄名稱的可列舉集合,並選擇性地搜尋子目錄。Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories.

Exists(String) Exists(String) Exists(String) Exists(String)

判斷指定路徑是否參考磁碟上的現有目錄。Determines whether the given path refers to an existing directory on disk.

GetAccessControl(String) GetAccessControl(String) GetAccessControl(String) GetAccessControl(String)

取得 DirectorySecurity 物件,該物件會封裝指定目錄的存取控制清單 (ACL) 項目。Gets a DirectorySecurity object that encapsulates the access control list (ACL) entries for a specified directory.

GetAccessControl(String, AccessControlSections) GetAccessControl(String, AccessControlSections) GetAccessControl(String, AccessControlSections) GetAccessControl(String, AccessControlSections)

取得 DirectorySecurity 物件,該物件會為指定的目錄封裝指定類型的存取控制清單 (ACL) 項目。Gets a DirectorySecurity object that encapsulates the specified type of access control list (ACL) entries for a specified directory.

GetCreationTime(String) GetCreationTime(String) GetCreationTime(String) GetCreationTime(String)

取得目錄的建立日期和時間。Gets the creation date and time of a directory.

GetCreationTimeUtc(String) GetCreationTimeUtc(String) GetCreationTimeUtc(String) GetCreationTimeUtc(String)

取得目錄的建立日期和時間,格式為國際標準時間 (UTC)。Gets the creation date and time, in Coordinated Universal Time (UTC) format, of a directory.

GetCurrentDirectory() GetCurrentDirectory() GetCurrentDirectory() GetCurrentDirectory()

取得應用程式的目前工作目錄。Gets the current working directory of the application.

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

傳回指定目錄中符合指定搜尋模式之子目錄 (包含其路徑) 的名稱,並且選擇性地搜尋子目錄。Returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories.

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

傳回指定之目錄中的子目錄名稱 (包括其路徑)。Returns the names of subdirectories (including their paths) in the specified directory.

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

傳回指定目錄中符合指定搜尋模式的子目錄名稱 (包括檔案的路徑)。Returns the names of subdirectories (including their paths) that match the specified search pattern in the specified directory.

GetDirectoryRoot(String) GetDirectoryRoot(String) GetDirectoryRoot(String) GetDirectoryRoot(String)

傳回指定路徑的磁碟區資訊、根目錄資訊或兩者。Returns the volume information, root information, or both for the specified path.

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

傳回指定目錄中的檔案名稱 (包括路徑)。Returns the names of files (including their paths) in the specified directory.

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

傳回指定目錄中符合指定搜尋模式的檔案名稱 (包括檔案的路徑)。Returns the names of files (including their paths) that match the specified search pattern in the specified directory.

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

傳回指定目錄中符合指定搜尋模式的檔案名稱 (包括檔案的路徑),並使用值判斷是否搜尋子目錄。Returns the names of files (including their paths) that match the specified search pattern in the specified directory, using a value to determine whether to search subdirectories.

GetFileSystemEntries(String) GetFileSystemEntries(String) GetFileSystemEntries(String) GetFileSystemEntries(String)

傳回指定路徑中所有檔案和子目錄的名稱。Returns the names of all files and subdirectories in a specified path.

GetFileSystemEntries(String, String) GetFileSystemEntries(String, String) GetFileSystemEntries(String, String) GetFileSystemEntries(String, String)

傳回符合指定路徑中搜尋模式的目錄名稱,及檔案名稱的陣列。Returns an array of file names and directory names that match a search pattern in a specified path.

GetFileSystemEntries(String, String, EnumerationOptions) GetFileSystemEntries(String, String, EnumerationOptions) GetFileSystemEntries(String, String, EnumerationOptions) GetFileSystemEntries(String, String, EnumerationOptions)
GetFileSystemEntries(String, String, SearchOption) GetFileSystemEntries(String, String, SearchOption) GetFileSystemEntries(String, String, SearchOption) GetFileSystemEntries(String, String, SearchOption)

傳回指定之路徑中符合搜尋模式之所有檔名和目錄名稱的陣列,並選擇性地搜尋子目錄。Returns an array of all the file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories.

GetLastAccessTime(String) GetLastAccessTime(String) GetLastAccessTime(String) GetLastAccessTime(String)

傳回指定檔案或目錄上次被存取的日期和時間。Returns the date and time the specified file or directory was last accessed.

GetLastAccessTimeUtc(String) GetLastAccessTimeUtc(String) GetLastAccessTimeUtc(String) GetLastAccessTimeUtc(String)

傳回上次存取指定檔案或目錄的日期和時間,格式為國際標準時間 (UTC)。Returns the date and time, in Coordinated Universal Time (UTC) format, that the specified file or directory was last accessed.

GetLastWriteTime(String) GetLastWriteTime(String) GetLastWriteTime(String) GetLastWriteTime(String)

傳回指定檔案或目錄上次被寫入的日期和時間。Returns the date and time the specified file or directory was last written to.

GetLastWriteTimeUtc(String) GetLastWriteTimeUtc(String) GetLastWriteTimeUtc(String) GetLastWriteTimeUtc(String)

傳回上次寫入指定檔案或目錄的日期和時間,格式為國際標準時間 (UTC)。Returns the date and time, in Coordinated Universal Time (UTC) format, that the specified file or directory was last written to.

GetLogicalDrives() GetLogicalDrives() GetLogicalDrives() GetLogicalDrives()

以 "<磁碟機代號>:\" 的形式來擷取這個電腦上邏輯磁碟機的名稱。Retrieves the names of the logical drives on this computer in the form "<drive letter>:\".

GetParent(String) GetParent(String) GetParent(String) GetParent(String)

擷取指定路徑的父目錄,包括絕對和相對路徑兩者。Retrieves the parent directory of the specified path, including both absolute and relative paths.

Move(String, String) Move(String, String) Move(String, String) Move(String, String)

移動檔案或目錄和其內容到新位置。Moves a file or a directory and its contents to a new location.

SetAccessControl(String, DirectorySecurity) SetAccessControl(String, DirectorySecurity) SetAccessControl(String, DirectorySecurity) SetAccessControl(String, DirectorySecurity)

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

SetCreationTime(String, DateTime) SetCreationTime(String, DateTime) SetCreationTime(String, DateTime) SetCreationTime(String, DateTime)

設定指定檔案或目錄建立的日期和時間。Sets the creation date and time for the specified file or directory.

SetCreationTimeUtc(String, DateTime) SetCreationTimeUtc(String, DateTime) SetCreationTimeUtc(String, DateTime) SetCreationTimeUtc(String, DateTime)

設定指定檔案或目錄的建立日期和時間,格式為國際標準時間 (UTC)。Sets the creation date and time, in Coordinated Universal Time (UTC) format, for the specified file or directory.

SetCurrentDirectory(String) SetCurrentDirectory(String) SetCurrentDirectory(String) SetCurrentDirectory(String)

將應用程式的目前工作目錄設定為指定目錄。Sets the application's current working directory to the specified directory.

SetLastAccessTime(String, DateTime) SetLastAccessTime(String, DateTime) SetLastAccessTime(String, DateTime) SetLastAccessTime(String, DateTime)

設定指定檔案或目錄上次被存取的日期和時間。Sets the date and time the specified file or directory was last accessed.

SetLastAccessTimeUtc(String, DateTime) SetLastAccessTimeUtc(String, DateTime) SetLastAccessTimeUtc(String, DateTime) SetLastAccessTimeUtc(String, DateTime)

設定上次存取指定檔案或目錄的日期和時間,格式為國際標準時間 (UTC)。Sets the date and time, in Coordinated Universal Time (UTC) format, that the specified file or directory was last accessed.

SetLastWriteTime(String, DateTime) SetLastWriteTime(String, DateTime) SetLastWriteTime(String, DateTime) SetLastWriteTime(String, DateTime)

設定目錄上次被寫入的日期和時間。Sets the date and time a directory was last written to.

SetLastWriteTimeUtc(String, DateTime) SetLastWriteTimeUtc(String, DateTime) SetLastWriteTimeUtc(String, DateTime) SetLastWriteTimeUtc(String, DateTime)

設定上次寫入目錄的日期和時間,格式為國際標準時間 (UTC)。Sets the date and time, in Coordinated Universal Time (UTC) format, that a directory was last written to.

適用於

另請參閱