.NET Framework Class Library
Directory..::.CreateDirectory Method (String)

Creates all directories and subdirectories as specified by path.

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)
Syntax

Visual Basic (Declaration)
Public Shared Function CreateDirectory ( _
    path As String _
) As DirectoryInfo
Visual Basic (Usage)
Dim path As String
Dim returnValue As DirectoryInfo

returnValue = Directory.CreateDirectory(path)
C#
public static DirectoryInfo CreateDirectory(
    string path
)
Visual C++
public:
static DirectoryInfo^ CreateDirectory(
    String^ path
)
JScript
public static function CreateDirectory(
    path : String
) : DirectoryInfo

Parameters

path
Type: System..::.String
The directory path to create.

Return Value

Type: System.IO..::.DirectoryInfo
A DirectoryInfo as specified by path.
Exceptions

ExceptionCondition
IOException

The directory specified by path is read-only.

UnauthorizedAccessException

The caller does not have the required permission.

ArgumentException

path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

-or-

path is prefixed with, or contains only a colon character (:).

ArgumentNullException

path is nullNothingnullptra null reference (Nothing in Visual Basic).

PathTooLongException

The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters and file names must be less than 260 characters.

DirectoryNotFoundException

The specified path is invalid (for example, it is on an unmapped drive).

NotSupportedException

path contains a colon character (:) that is not part of a drive label ("C:\").

Remarks

Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.

Creating a directory with only the colon (:) character is not supported, and will cause a NotSupportedException to be thrown.

For a list of common I/O tasks, see Common I/O Tasks.

Examples

The following code example creates and deletes the specified directory.

Visual Basic
Imports System
Imports System.IO
Imports Microsoft.VisualBasic

Public Class Test
    Public Shared Sub Main()
        ' Specify the directory you want to manipulate.
        Dim path As String = "c:\MyDir"

        Try
            ' Determine whether the directory exists.
            If Directory.Exists(path) Then
                Console.WriteLine("That path exists already.")
                Return
            End If

            ' Try to create the directory.
            Dim di As DirectoryInfo = Directory.CreateDirectory(path)
            Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path))

            ' 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
C#
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        // Specify the directory you want to manipulate.
        string path = @"c:\MyDir";

        try 
        {
            // Determine whether the directory exists.
            if (Directory.Exists(path)) 
            {
                Console.WriteLine("That path exists already.");
                return;
            }

            // Try to create the directory.
            DirectoryInfo di = Directory.CreateDirectory(path);
            Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));

            // Delete the directory.
            di.Delete();
            Console.WriteLine("The directory was deleted successfully.");
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        } 
        finally {}
    }
}
Visual C++
using namespace System;
using namespace System::IO;
int main()
{

   // Specify the directory you want to manipulate.
   String^ path = "c:\\MyDir";
   try
   {

      // Determine whether the directory exists.
      if ( Directory::Exists( path ) )
      {
         Console::WriteLine( "That path exists already." );
         return 0;
      }

      // Try to create the directory.
      DirectoryInfo^ di = Directory::CreateDirectory( path );
      Console::WriteLine( "The directory was created successfully at {0}.", Directory::GetCreationTime( path ) );

      // Delete the directory.
      di->Delete();
      Console::WriteLine( "The directory was deleted successfully." );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }

}

To create the directory C:\Users\User1\Public\Html when the current directory is C:\Users\User1, use any of the following calls to ensure that the backslash is interpreted properly.

In Visual Basic:

 Directory.CreateDirectory("Public\Html") 
     Directory.CreateDirectory("\Users\User1\Public\Html") 
     Directory.CreateDirectory("c:\Users\User1\Public\Html")

In C#:

 Directory.CreateDirectory("Public\\Html");
     Directory.CreateDirectory("\\Users\\User1\\Public\\Html");
     Directory.CreateDirectory("c:\\Users\\User1\\Public\\Html");

In C++:

 Directory::CreateDirectory("Public\\Html");
     Directory::CreateDirectory("\\Users\\User1\\Public\\Html");
     Directory::CreateDirectory("c:\\Users\\User1\\Public\\Html");
.NET Framework Security

Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

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

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
See Also

Reference

Other Resources

Tags :


Community Content

Poshoholic
Sample Using PowerShell
<#
.SYNOPSIS
This script Creates then removes a folder using methods in
System.IO.Directory.
.DESCRIPTION
This script checks to see if a staticly named folder exists.
if not, it creates then removes the folder. The creation/deletion
logic in enclosed within a try/catch block to capture errors.
.NOTES
File Name : New-Folder.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell V2
.LINK
This script posted to:
http://www.pshscripts.blogspot.com
MSDN Sample posted at:
http://msdn.microsoft.com/en-us/library/54a0at6s.aspx
.EXAMPLE
PSH [C:\foo]: .\New-Folder.ps1'
The directory was created successfully at 09/10/2009 9:30:58 AM.
The directory was deleted successfully.
#>

# Specify the directory to manipulate
$path = "c:\fooxx"

try {
# try to see if the directory exists (It should not!)
if ([system.io.Directory]::Exists($path)) {
"That path exists already."
return
}

# Try to create the directory
$di = [System.Io.Directory]::CreateDirectory($path)

# Get creattion time and display results
$dit = [System.IO.Directory]::GetCreationTime($path)
"The directory was created successfully at {0}." -f $dit

# Delete the directory
$di.Delete()
"The directory was deleted successfully."
}
catch {
"The process failed"
}

Page view tracker