Saturday, 26 January 2013

Create a Sub Directories using C#

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()
tags:Creating a sub directories in C#,Creating a sub directory in C#,Creating a sub folder in C#,Creating a sub folders in C#,Create a directory in C#, Creating a directory in C#, Create a folder in C#,How to create a directory in C#,How to Create directory using DirectoryInfo, System.IO.Directory.CreateDirectory, System.IO.DirectoryInfo.CreateSubdirectory, Directory.GetCurrentDirectory.