1 out of 2 rated this helpful - Rate this topic

DirectoryInfo Class

Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.

System.Object
  System.MarshalByRefObject
    System.IO.FileSystemInfo
      System.IO.DirectoryInfo

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)
[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class DirectoryInfo : FileSystemInfo

The DirectoryInfo type exposes the following members.

  Name Description
Public method Supported by the XNA Framework DirectoryInfo Initializes a new instance of the DirectoryInfo class on the specified path.
Top
  Name Description
Public property Supported by the XNA Framework Attributes Gets or sets the attributes for the current file or directory. (Inherited from FileSystemInfo.)
Public property Supported by the XNA Framework CreationTime Gets or sets the creation time of the current file or directory. (Inherited from FileSystemInfo.)
Public property CreationTimeUtc Gets or sets the creation time, in coordinated universal time (UTC), of the current file or directory. (Inherited from FileSystemInfo.)
Public property Supported by the XNA Framework Exists Gets a value indicating whether the directory exists. (Overrides FileSystemInfo.Exists.)
Public property Supported by the XNA Framework Extension Gets the string representing the extension part of the file. (Inherited from FileSystemInfo.)
Public property Supported by the XNA Framework FullName Gets the full path of the directory or file. (Inherited from FileSystemInfo.)
Public property Supported by the XNA Framework LastAccessTime Gets or sets the time the current file or directory was last accessed. (Inherited from FileSystemInfo.)
Public property LastAccessTimeUtc Gets or sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed. (Inherited from FileSystemInfo.)
Public property Supported by the XNA Framework LastWriteTime Gets or sets the time when the current file or directory was last written to. (Inherited from FileSystemInfo.)
Public property LastWriteTimeUtc Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to. (Inherited from FileSystemInfo.)
Public property Supported by the XNA Framework Name Gets the name of this DirectoryInfo instance. (Overrides FileSystemInfo.Name.)
Public property Supported by the XNA Framework Parent Gets the parent directory of a specified subdirectory.
Public property Supported by the XNA Framework Root Gets the root portion of a path.
Top
  Name Description
Public method Supported by the XNA Framework Create() Creates a directory.
Public method Create(DirectorySecurity) Creates a directory using a DirectorySecurity object.
Public method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method Supported by the XNA Framework CreateSubdirectory(String) Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class.
Public method 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 the DirectoryInfo class.
Public method Supported by the XNA Framework Delete() Deletes this DirectoryInfo if it is empty. (Overrides FileSystemInfo.Delete().)
Public method Supported by the XNA Framework Delete(Boolean) Deletes this instance of a DirectoryInfo, specifying whether to delete subdirectories and files.
Public method EnumerateDirectories() Returns an enumerable collection of directory information in the current directory.
Public method EnumerateDirectories(String) Returns an enumerable collection of directory information that matches a specified search pattern.
Public method EnumerateDirectories(String, SearchOption) Returns an enumerable collection of directory information that matches a specified search pattern and search subdirectory option.
Public method EnumerateFiles() Returns an enumerable collection of file information in the current directory.
Public method EnumerateFiles(String) Returns an enumerable collection of file information that matches a search pattern.
Public method EnumerateFiles(String, SearchOption) Returns an enumerable collection of file information that matches a specified search pattern and search subdirectory option.
Public method EnumerateFileSystemInfos() Returns an enumerable collection of file system information in the current directory.
Public method EnumerateFileSystemInfos(String) Returns an enumerable collection of file system information that matches a specified search pattern.
Public method EnumerateFileSystemInfos(String, SearchOption) Returns an enumerable collection of file system information that matches a specified search pattern and search subdirectory option.
Public method Supported by the XNA Framework Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by the XNA Framework Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetAccessControl() Gets a DirectorySecurity object that encapsulates the access control list (ACL) entries for the directory described by the current DirectoryInfo object.
Public method GetAccessControl(AccessControlSections) Gets a DirectorySecurity object that encapsulates the specified type of access control list (ACL) entries for the directory described by the current DirectoryInfo object.
Public method Supported by the XNA Framework GetDirectories() Returns the subdirectories of the current directory.
Public method Supported by the XNA Framework GetDirectories(String) Returns an array of directories in the current DirectoryInfo matching the given search criteria.
Public method GetDirectories(String, SearchOption) Returns an array of directories in the current DirectoryInfo matching the given search criteria and using a value to determine whether to search subdirectories.
Public method Supported by the XNA Framework GetFiles() Returns a file list from the current directory.
Public method Supported by the XNA Framework GetFiles(String) Returns a file list from the current directory matching the given search pattern.
Public method 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.
Public method Supported by the XNA Framework GetFileSystemInfos() Returns an array of strongly typed FileSystemInfo entries representing all the files and subdirectories in a directory.
Public method Supported by the XNA Framework GetFileSystemInfos(String) Retrieves an array of strongly typed FileSystemInfo objects representing the files and subdirectories that match the specified search criteria.
Public method GetFileSystemInfos(String, SearchOption) Retrieves an array of FileSystemInfo objects that represent the files and subdirectories matching the specified search criteria.
Public method Supported by the XNA Framework GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public method GetObjectData Sets the SerializationInfo object with the file name and additional exception information. (Inherited from FileSystemInfo.)
Public method Supported by the XNA Framework GetType Gets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method Supported by the XNA Framework MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public method Supported by the XNA Framework MoveTo Moves a DirectoryInfo instance and its contents to a new path.
Public method Supported by the XNA Framework Refresh Refreshes the state of the object. (Inherited from FileSystemInfo.)
Public method SetAccessControl Applies access control list (ACL) entries described by a DirectorySecurity object to the directory described by the current DirectoryInfo object.
Public method Supported by the XNA Framework ToString Returns the original path that was passed by the user. (Overrides Object.ToString().)
Top
  Name Description
Protected field Supported by the XNA Framework FullPath Represents the fully qualified path of the directory or file. (Inherited from FileSystemInfo.)
Protected field Supported by the XNA Framework OriginalPath The path originally specified by the user, whether relative or absolute. (Inherited from FileSystemInfo.)
Top

Use the DirectoryInfo 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 of DirectoryInfo instead of the corresponding static methods of the Directory class, because a security check will not always be necessary.

Note 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, see Common I/O Tasks.

The following example demonstrates some of the main members of the DirectoryInfo 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 {}
    }
}


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


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Directory/DirectoryInfo incorrect work with directories with space(s) in end of name (UNC issue)
The main issue is space in end of the directory name, which Directory/DirectoryInfo classes ignore. The all methods of the Directory/DirectoryInfo use the NormalizePath of the Path class where the spaces trimmed (path.TrimEnd(TrimEndChars), the next code  generate the IllegalPath on UNC pathes (or PathTooLong when path longer than 260 chars)), it's properly because Explorer and WinApi methods don't allow in regular way make the directories with space(s) on end, but in practice it's quite antoher (any thirdparty shell explorer supporting UNC, or using UNC pathes methods allow make those directories). Do you have any idea how to work with directories with space(s) in end of name? (or possible know when NET Framework implement support UNC pathes? ) $0$0 $0 $0some example:
        string disk = @"C:\";
        foreach(string dir in Directory.GetDirectories(disk)) 
        {
            if(!dir.StartsWith(disk+"DirwithSpace")) continue;
            Console.WriteLine("\"{0}\", DirectoryInfo Name: \"{1}\", FullName: \"{2}\"", dir, new DirectoryInfo(dir).Name, new DirectoryInfo(dir).FullName);
            if(!Directory.Exists(dir)) {
                Console.WriteLine("Directory doesn't exists: \"{0}\"", dir);
                continue;
            }
        }
---
output
"C:\DirwithSpace ", DirectoryInfo Name: "DirwithSpace", FullName: "C:\DirwithSpace"
Directory doesn't exists: "C:\DirwithSpace "

How to make the directory name with spaces:
1. Using thridparty shells (Explore trim the space in end of the directory name)

2. VBScript
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateFolder("\\?\c:\DirwithSpace ")

3. C++/C#
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool CreateDirectory(string lpPathName, IntPtr lpSecurityAttributes); 
...
if (!CreateDirectory(@"\\?\C:\DirwithSpace  ", IntPtr.Zero)) throw new Win32Exception();
$0
$0 $0
DirectoryInfo() failes with Unicode paths
How would one get the ACL from Unicode paths (paths not limited bij the MAX_PATH lenght)

It seems that DirectoryInfo() doesn't it very well when paths are supplied with prefix: \\?\  or \\?\UNC\