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:

  • 在 Visual Basic 中\ C#的 "c: \MyDir" 或 "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.

  • 中\的 "\ C#\MyServer \MyShare", 或\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. 不過, 應用程式必須具有正確的安全性, 才能存取現有的目錄。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 Store 應用程式)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 they 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.

適用於

另請參閱