C# Create Directory

C# Create Directory

You can create directory using your own program written in .net languages.
The namespace System.Io provides such features. Following code snippets explains various scenarios. Create

Create Directory at application execution path.


using System;
using System.IO;
namespace ConsoleApplication
{    
class Program    
{        
static void Main(string[] args)        
{            
string currentExecutablepath = Directory.GetCurrentDirectory();            
string directoryName = "MySetup";            
string path = currentExecutablepath + @"\" + directoryName;            
Directory.CreateDirectory(path);            
Console.ReadKey();        
}         
}
}

   The above program created directory called MySetup at below path.

D:\demo\ConsoleApplication\ConsoleApplication\bin\Debug

Create Directory at root drive C:\

using System;
using System.IO;
namespace ConsoleApplication
{    
class Program    
{        
static void Main(string[] args)        
{            
Directory.CreateDirectory(@"c:\MyDirectory");            
Console.ReadKey();        
}         
}
}

c# create directory if it doesn't exist

using System;
using System.IO;
namespace ConsoleApplication
{    
class Program    
{        
static void Main(string[] args)        
{            
if( ! Directory.Exists(@"c:\MyDirectory"))            
{                            
Directory.CreateDirectory(@"c:\MyDirectory");            
}            
Console.WriteLine("Directory already exists.");            
Console.ReadKey();        
}         
}
}

Description: 

Directory.GetCurrentDirectory();  gives current directory execution path.

For more information about c# get current directory of executable

Directory.Exists(@"c:\MyDirectory"); Returns boolean value of whether directory exists at or not.

Summery:
  CreateDirectory is static method of class Directory. System.IO is the required namespace for
  File I/O operations.

Note: While dealing with File I/O operations there are possibilities of getting exception based on environment rights like create directory rights etc.
Based on those exceptions you can create log file or alert users about those exception and user can take appropriate actions.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5