Directory 类

定义

公开用于通过目录和子目录进行创建、移动和枚举的静态方法。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
继承
Directory
属性

示例

以下示例演示了如何从目录中检索所有文本文件,并将其移动到新目录。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.

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

  • \中的 "\\\\MyServer\C#\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 应用商店应用)For information about how to access files and folders in Windows 应用商店Windows Store apps, see Accessing data and files (Windows Store apps).

方法

CreateDirectory(String)

在指定路径中创建所有目录和子目录,除非它们已经存在。Creates all directories and subdirectories in the specified path unless they already exist.

CreateDirectory(String, DirectorySecurity)

在指定路径中创建所有目录(除非已存在),并应用指定的 Windows 安全性。Creates all the directories in the specified path, unless they already exist, applying the specified Windows security.

Delete(String)

从指定路径删除空目录。Deletes an empty directory from a specified path.

Delete(String, Boolean)

删除指定的目录,并删除该目录中的所有子目录和文件(如果表示)。Deletes the specified directory and, if indicated, any subdirectories and files in the directory.

EnumerateDirectories(String)

返回指定路径中的目录完整名称的可枚举集合。Returns an enumerable collection of directory full names in a specified path.

EnumerateDirectories(String, String)

返回指定路径中与搜索模式匹配的目录完整名称的可枚举集合。Returns an enumerable collection of directory full names that match a search pattern in a specified path.

EnumerateDirectories(String, String, EnumerationOptions)

返回指定路径中与搜索模式匹配的目录完整名称的可枚举集合,还可搜索子目录。Returns an enumerable collection of the directory full names that match a search pattern in a specified path, and optionally searches subdirectories.

EnumerateDirectories(String, String, SearchOption)

返回指定路径中与搜索模式匹配的目录完整名称的可枚举集合,还可搜索子目录。Returns an enumerable collection of directory full names that match a search pattern in a specified path, and optionally searches subdirectories.

EnumerateFiles(String)

返回指定路径中的完整文件名的可枚举集合。Returns an enumerable collection of full file names in a specified path.

EnumerateFiles(String, String)

返回指定路径中与搜索模式匹配的完整文件名的可枚举集合。Returns an enumerable collection of full file names that match a search pattern in a specified path.

EnumerateFiles(String, String, EnumerationOptions)

返回指定路径中与搜索模式和枚举选项匹配的完整文件名的可枚举集合,还可以搜索子目录。Returns an enumerable collection of full file names that match a search pattern and enumeration options in a specified path, and optionally searches subdirectories.

EnumerateFiles(String, String, SearchOption)

返回指定路径中与搜索模式匹配的完整文件名的可枚举集合,还可以搜索子目录。Returns an enumerable collection of full file names that match a search pattern in a specified path, and optionally searches subdirectories.

EnumerateFileSystemEntries(String)

返回指定路径中的文件名和目录名的可枚举集合。Returns an enumerable collection of file names and directory names in a specified path.

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)

返回指定路径中与搜索模式和枚举选项匹配的文件名和目录名的可枚举集合。Returns an enumerable collection of file names and directory names that match a search pattern and enumeration options in a specified path.

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)

确定给定路径是否引用磁盘上的现有目录。Determines whether the given path refers to an existing directory on disk.

GetAccessControl(String)

获取 DirectorySecurity 对象,该对象封装指定目录的访问控制列表 (ACL) 项。Gets a DirectorySecurity object that encapsulates the access control list (ACL) entries for a specified directory.

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)

获取目录的创建日期和时间。Gets the creation date and time of a directory.

GetCreationTimeUtc(String)

获取目录创建的日期和时间,其格式为协调通用时 (UTC)。Gets the creation date and time, in Coordinated Universal Time (UTC) format, of a directory.

GetCurrentDirectory()

获取应用程序的当前工作目录。Gets the current working directory of the application.

GetDirectories(String)

返回指定目录中的子目录的名称(包括其路径)。Returns the names of subdirectories (including their paths) in the specified directory.

GetDirectories(String, String)

返回指定目录中与指定的搜索模式匹配的子目录的名称(包括其路径)。Returns the names of subdirectories (including their paths) that match the specified search pattern in the specified directory.

GetDirectories(String, String, EnumerationOptions)

返回指定目录中与指定的搜索模式和枚举选项匹配的子目录的名称(包括其路径)。Returns the names of subdirectories (including their paths) that match the specified search pattern and enumeration options in the specified directory.

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.

GetDirectoryRoot(String)

返回指定路径的卷信息、根信息或两者同时返回。Returns the volume information, root information, or both for the specified path.

GetFiles(String)

返回指定目录中文件的名称(包括其路径)。Returns the names of files (including their paths) in the specified directory.

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)

返回指定目录中与指定的搜索模式和枚举选项匹配的文件的名称(包括其路径)。Returns the names of files (including their paths) that match the specified search pattern and enumeration options in the specified directory.

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)

返回指定路径中的所有文件和子目录的名称。Returns the names of all files and subdirectories in a specified path.

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)

返回指定路径中与搜索模式和枚举选项匹配的文件名和目录名的数组。Returns an array of file names and directory names that match a search pattern and enumeration options in a specified path.

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)

返回上次访问指定文件或目录的日期和时间。Returns the date and time the specified file or directory was last accessed.

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)

返回上次写入指定文件或目录的日期和时间。Returns the date and time the specified file or directory was last written to.

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

检索此计算机上格式为“<drive letter>:\”的逻辑驱动器的名称。Retrieves the names of the logical drives on this computer in the form "<drive letter>:\".

GetParent(String)

检索指定路径的父目录,包括绝对路径和相对路径。Retrieves the parent directory of the specified path, including both absolute and relative paths.

Move(String, String)

将文件或目录及其内容移到新位置。Moves a file or a directory and its contents to a new location.

SetAccessControl(String, DirectorySecurity)

DirectorySecurity 对象描述的访问控制列表 (ACL) 项应用于指定的目录。Applies access control list (ACL) entries described by a DirectorySecurity object to the specified directory.

SetCreationTime(String, DateTime)

为指定的文件或目录设置创建日期和时间。Sets the creation date and time for the specified file or directory.

SetCreationTimeUtc(String, DateTime)

设置指定文件或目录的创建日期和时间,其格式为协调通用时 (UTC)。Sets the creation date and time, in Coordinated Universal Time (UTC) format, for the specified file or directory.

SetCurrentDirectory(String)

将应用程序的当前工作目录设置为指定的目录。Sets the application's current working directory to the specified directory.

SetLastAccessTime(String, DateTime)

设置上次访问指定文件或目录的日期和时间。Sets the date and time the specified file or directory was last accessed.

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)

设置上次写入目录的日期和时间。Sets the date and time a directory was last written to.

SetLastWriteTimeUtc(String, DateTime)

设置上次写入某个目录的日期和时间,其格式为协调通用时 (UTC)。Sets the date and time, in Coordinated Universal Time (UTC) format, that a directory was last written to.

适用于

另请参阅