Create a Sub Directories using C#
Creating a Sub directory in C# can be done by two ways
1. Static method part of Directory Class CreateDirectory
2.Instance method of DirectoryInfo CreateSubdirectory.
Before that Call using System.IO;
Calling
CreateSubDirectory(@"c:\personal", "Excel Files");
Method1 - Directory Static method
static void CreateSubDirectory(String src,String subDir){
try
{
Directory.CreateDirectory(Path.Combine(src, subDir));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Method 2 - DirectoryInfo Instance Method
static void CreateSubDirectory(String src,String subDir){
try
{
DirectoryInfo dInfo = new DirectoryInfo(src);
//Here relative path should be given i.e just folder name i.e "Excel Files"
dInfo.CreateSubdirectory(subDir);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//output
C:\personal\Excel files\
- Creating already existing sub directory nothing will happen(no content will be erased).
- If main directory doesn't exists , in that case src directory will be created then sub directory.
- 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