This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.
public ref class DirectoryInfo sealed : System::IO::FileSystemInfopublic sealed class DirectoryInfo : System.IO.FileSystemInfo[System.Serializable]public sealed class DirectoryInfo : System.IO.FileSystemInfo[System.Serializable][System.Runtime.InteropServices.ComVisible(true)]public sealed class DirectoryInfo : System.IO.FileSystemInfotype DirectoryInfo = class inherit FileSystemInfo[<System.Serializable>]type DirectoryInfo = class inherit FileSystemInfo[<System.Serializable>][<System.Runtime.InteropServices.ComVisible(true)>]type DirectoryInfo = class inherit FileSystemInfoPublic NotInheritable Class DirectoryInfoInherits FileSystemInfoThe following example demonstrates some of the main members of theDirectoryInfo class.
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 {} }}open System.IO// Specify the directories you want to manipulate.let di = DirectoryInfo @"c:\MyDir"try // Determine whether the directory exists. if di.Exists then // Indicate that the directory already exists. printfn "That path exists already." else // Try to create the directory. di.Create() printfn "The directory was created successfully." // Delete the directory. di.Delete() printfn "The directory was deleted successfully."with e -> printfn $"The process failed: {e}"Imports System.IOPublic 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 SubEnd ClassThe 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)) { 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.}open System.IOlet rec copyAll (source: DirectoryInfo) (target: DirectoryInfo) = if source.FullName.ToLower() <> target.FullName.ToLower() then // Check if the target directory exists, if not, create it. if not (Directory.Exists target.FullName) then Directory.CreateDirectory target.FullName |> ignore // Copy each file into it's new directory. for fi in source.GetFiles() do printfn $@"Copying {target.FullName}\{fi.Name}" fi.CopyTo(Path.Combine(string target, fi.Name), true) |> ignore // Copy each subdirectory using recursion. for diSourceSubDir in source.GetDirectories() do target.CreateSubdirectory diSourceSubDir.Name |> copyAll diSourceSubDirlet sourceDirectory = @"c:\sourceDirectory"let targetDirectory = @"c:\targetDirectory"let diSource = DirectoryInfo sourceDirectorylet diTarget = DirectoryInfo targetDirectorycopyAll diSource diTarget// Output will vary based on the contents of the source directory.Imports System.IOClass 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 ClassUse theDirectoryInfo class for typical operations such as copying, moving, renaming, creating, and deleting directories.
If you are going to reuse an object several times, consider using the instance method ofDirectoryInfo instead of the corresponding static methods of theDirectory class, because a security check will not always be necessary.
Note
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. 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. 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\\MyFile.txt" in C#, or "c:\MyDir\MyFile.txt" in Visual Basic.
"c:\\MyDir" in C#, or "c:\MyDir" in Visual Basic.
"MyDir\\MySubdir" in C#, or "MyDir\MySubDir" in 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.
For a list of common I/O tasks, seeCommon I/O Tasks.
| Name | Description |
|---|---|
| DirectoryInfo(String) | Initializes a new instance of theDirectoryInfo class on the specified path. |
| Name | Description |
|---|---|
| FullPath | Represents the fully qualified path of the directory or file. (Inherited fromFileSystemInfo) |
| OriginalPath | The path originally specified by the user, whether relative or absolute. (Inherited fromFileSystemInfo) |
| Name | Description |
|---|---|
| Attributes | Gets or sets the attributes for the current file or directory. (Inherited fromFileSystemInfo) |
| CreationTime | Gets or sets the creation time of the current file or directory. (Inherited fromFileSystemInfo) |
| CreationTimeUtc | Gets or sets the creation time, in coordinated universal time (UTC), of the current file or directory. (Inherited fromFileSystemInfo) |
| Exists | Gets a value indicating whether the directory exists. |
| Extension | Gets the extension part of the file name, including the leading dot |
| FullName | Gets the full path of the directory. |
| FullName | Gets the full path of the directory or file. (Inherited fromFileSystemInfo) |
| LastAccessTime | Gets or sets the time the current file or directory was last accessed. (Inherited fromFileSystemInfo) |
| LastAccessTimeUtc | Gets or sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed. (Inherited fromFileSystemInfo) |
| LastWriteTime | Gets or sets the time when the current file or directory was last written to. (Inherited fromFileSystemInfo) |
| LastWriteTimeUtc | Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to. (Inherited fromFileSystemInfo) |
| LinkTarget | Gets the target path of the link located inFullName, or |
| Name | Gets the name of thisDirectoryInfo instance. |
| Parent | Gets the parent directory of a specified subdirectory. |
| Root | Gets the root portion of the directory. |
| UnixFileMode | Gets or sets the Unix file mode for the current file or directory. (Inherited fromFileSystemInfo) |
| Name | Description |
|---|---|
| Create() | Creates a directory. |
| Create(DirectorySecurity) | Creates a directory using aDirectorySecurity object. |
| CreateAsSymbolicLink(String) | Creates a symbolic link located inFullName that points to the specified |
| CreateObjRef(Type) | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited fromMarshalByRefObject) |
| CreateSubdirectory(String, DirectorySecurity) | Creates a subdirectory or subdirectories on the specified path with the specified security. The specified path can be relative to this instance of theDirectoryInfo class. |
| CreateSubdirectory(String) | Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of theDirectoryInfo class. |
| Delete() | Deletes thisDirectoryInfo if it is empty. |
| Delete(Boolean) | Deletes this instance of aDirectoryInfo, specifying whether to delete subdirectories and files. |
| EnumerateDirectories() | Returns an enumerable collection of directory information in the current directory. |
| 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. |
| EnumerateDirectories(String) | Returns an enumerable collection of directory information that matches a specified search pattern. |
| EnumerateFiles() | Returns an enumerable collection of file information in the current directory. |
| 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. |
| EnumerateFiles(String) | Returns an enumerable collection of file information that matches a search pattern. |
| EnumerateFileSystemInfos() | Returns an enumerable collection of file system information in the current directory. |
| 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. |
| EnumerateFileSystemInfos(String) | Returns an enumerable collection of file system information that matches a specified search pattern. |
| Equals(Object) | Determines whether the specified object is equal to the current object. (Inherited fromObject) |
| GetAccessControl() | Gets aDirectorySecurity object that encapsulates the access control list (ACL) entries for the directory described by the currentDirectoryInfo object. |
| GetAccessControl(AccessControlSections) | Gets aDirectorySecurity object that encapsulates the specified type of access control list (ACL) entries for the directory described by the currentDirectoryInfo object. |
| GetDirectories() | Returns the subdirectories of the current directory. |
| GetDirectories(String, EnumerationOptions) | Returns an array of directories in the currentDirectoryInfo matching the specified search pattern and enumeration options. |
| GetDirectories(String, SearchOption) | Returns an array of directories in the currentDirectoryInfo matching the given search criteria and using a value to determine whether to search subdirectories. |
| GetDirectories(String) | Returns an array of directories in the currentDirectoryInfo matching the given search criteria. |
| GetFiles() | Returns a file list from the current directory. |
| 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. |
| GetFiles(String) | Returns a file list from the current directory matching the given search pattern. |
| GetFileSystemInfos() | Returns an array of strongly typedFileSystemInfo entries representing all the files and subdirectories in a directory. |
| GetFileSystemInfos(String, EnumerationOptions) | Retrieves an array of strongly typedFileSystemInfo objects representing the files and subdirectories that match the specified search pattern and enumeration options. |
| GetFileSystemInfos(String, SearchOption) | Retrieves an array ofFileSystemInfo objects that represent the files and subdirectories matching the specified search criteria. |
| GetFileSystemInfos(String) | Retrieves an array of strongly typedFileSystemInfo objects representing the files and subdirectories that match the specified search criteria. |
| GetHashCode() | Serves as the default hash function. (Inherited fromObject) |
| GetLifetimeService() | Obsolete. Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited fromMarshalByRefObject) |
| GetObjectData(SerializationInfo, StreamingContext) | Obsolete. Sets theSerializationInfo object with the file name and additional exception information. (Inherited fromFileSystemInfo) |
| GetType() | Gets theType of the current instance. (Inherited fromObject) |
| InitializeLifetimeService() | Obsolete. Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited fromMarshalByRefObject) |
| MemberwiseClone() | Creates a shallow copy of the currentObject. (Inherited fromObject) |
| MemberwiseClone(Boolean) | Creates a shallow copy of the currentMarshalByRefObject object. (Inherited fromMarshalByRefObject) |
| MoveTo(String) | Moves aDirectoryInfo instance and its contents to a new path. |
| Refresh() | Refreshes the state of the object. (Inherited fromFileSystemInfo) |
| ResolveLinkTarget(Boolean) | Gets the target of the specified link. (Inherited fromFileSystemInfo) |
| SetAccessControl(DirectorySecurity) | Applies access control list (ACL) entries described by aDirectorySecurity object to the directory described by the currentDirectoryInfo object. |
| ToString() | Returns the original path that was passed to theDirectoryInfo constructor. Use theFullName orName properties for the full path or file/directory name instead of this method. |
| ToString() | Returns the original path. Use theFullName orName properties for the full path or file/directory name. (Inherited fromFileSystemInfo) |
| Name | Description |
|---|---|
| Create(DirectoryInfo, DirectorySecurity) | Creates a new directory, ensuring it is created with the specified directory security. If the directory already exists, nothing is done. |
| GetAccessControl(DirectoryInfo, AccessControlSections) | Returns the security information of a directory. |
| GetAccessControl(DirectoryInfo) | Returns the security information of a directory. |
| SetAccessControl(DirectoryInfo, DirectorySecurity) | Changes the security attributes of an existing directory. |
Was this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?