Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Create a Directory in CSharp

In C#, DirectoryInfo and Directory classes represent a folder on the file system. This example explains how to use these classes to create a directory with time stamp and rename directory if the directory exists. 

 

using System;
using System.IO;

namespace Com.Example.Csharp
{
    class CreateFolder
    {
        static void Main(string[] args)
        {
            
           //create folder
            CreateFolder folder1=new CreateFolder();
           folder1.CreateANewFolder("test","folder1");
            
            //create folder
            CreateFolder folder2=new CreateFolder();
           folder2.CreateANewFolder("test", "folder2");

            //create folder and rename existing
            CreateFolder folder3=new CreateFolder();
            folder3.CreateANewFolderRenameExisting("test","folder");
        }

        public void CreateANewFolder(String folderPrefix, String folderSuffix)
        {
            //get current system data and time
            DateTime currentDateTime = DateTime.Now;
            //convert current system date and time to a string
            string currentDataTimeString = currentDateTime.ToString("yyyy_MM_dd_hh_mm_ss_tt", System.Globalization.CultureInfo.InvariantCulture);
            //create a new folder 
            string newFolder = folderPrefix+"_" + currentDataTimeString+"_"+folderSuffix;
            System.IO.Directory.CreateDirectory(newFolder);
        }
        public void CreateANewFolderRenameExisting(String folderPrefix, String folderSuffix)
        {
            //create a new folder 
            string newFolder = folderPrefix + "_" + folderSuffix;
            DirectoryInfo directoryInfo=new DirectoryInfo(newFolder);
            if(!directoryInfo.Exists)
            System.IO.Directory.CreateDirectory(newFolder);
            else
            {
                directoryInfo.MoveTo(directoryInfo.FullName+"backup");
                System.IO.Directory.CreateDirectory(newFolder);
            }
        }
    }
}

Run the above code and see the results below. If you run the above code in "Debug" mode, you will see these folders in the bin\Debug folder.

test_2015_07_06_08_22_32_PM_folder1
test_2015_07_06_08_22_32_PM_folder2
test_folder
test_folderbackup