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

检索此计算机上格式为“<drive letter>:\”的逻辑驱动器的名称。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.

适用于

另请参阅