Create a Directory in C#
Creating a directory in C# can be done by two ways
1. Static method part of Directory Class CreateDirectory
2.Instance method of DirectoryInfo Create.
Before that Call using System.IO;
Calling
CreateDirectory(@"C:\personal");
Method1 - Directory Static method
static void CreateDirectory(String dir){
try
{
if (!Directory.Exists(dir))
{
DirectoryInfo dInfo = Directory.CreateDirectory(dir);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Method 2 - DirectoryInfo Instance Method
static void CreateDirectory(String dir){
try
{
if (!Directory.Exists(dir))
{
DirectoryInfo dd = new DirectoryInfo(dir);
dd.Create();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
- Creating already existing directory nothing will happen(no content will be erased).
- Directory name should contain volume label C:\ or D:\ otherwise Directory will be created in the current folder. In order to get Current Directory call Directory.GetCurrentDirectory()
No comments:
Post a Comment