DirectoryInfo 类

定义

公开用于创建、移动和枚举目录和子目录的实例方法。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:\\MyDir\" 中C#的 "\MyFile.txt" 或 "c:\MyDir\MyFile.txt" 中的 Visual Basic。"c:\\MyDir\\MyFile.txt" in C#, or "c:\MyDir\MyFile.txt" in Visual Basic.

  • 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.

有关常见 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

获取或设置当前文件或目录的创建时间,其格式为协调世界时 (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

获取或设置上次访问当前文件或目录的时间,其格式为协调世界时 (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

获取或设置上次写入当前文件或目录的时间,其格式为协调世界时 (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

获取指定的子目录的父目录。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)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。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()

检索控制此实例的生存期策略的当前生存期服务对象。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)

适用于

另请参阅