Wednesday, April 10, 2013

ASP.Net- Creating Directory in C# | Creating Folder in C#

In this post, I will explain how to create , delete directory or folder using C#.

In my previous posts, I explained Check Internet Connection using C#, SQL Server Database BackUp using C#, Partial Methods, Contextual Keyword, C# Static Methods and some other articles related to C#, ASP.Net and SQL Server .

For creating, deleting directory using C#, First of all you will have to add the following namespace in your code file.

using System.IO;

After adding the above namespace, write the following code for creating, deleting the directory.

 

Code for Create new directory

 

/// <summary>
/// Method for delete directory
/// </summary>
/// <param name="directoryName">Name of directory to be created</param>
public static void CreateNewDirectory(string directoryName)
{
   try
   {
     string strPath = @"C:/" + directoryName;
     //Check that directory with same is exists or not
     if (!(Directory.Exists(strPath)))
     {
         //Creating new directory
         Directory.CreateDirectory(strPath);
         Console.WriteLine("Directory Created Successfully");
         Console.ReadKey();                  
     }
     else
     {
        Console.WriteLine("Directory with same name already exists");
        Console.ReadKey();
     }
    }
    catch (Exception ex)
    {
    }
}

 

Code for Delete Directory

 

/// <summary>
/// Method for delete directory
/// </summary>
/// <param name="directoryName">Name of directory to be deleted</param>
public static void DeleteDirectory(string directoryName)
{
   try
   {
      string strPath = @"C:/" + directoryName;
      //Check that directory with same is exists or not
      if (Directory.Exists(strPath))
      {
        //Delete directory
        Directory.Delete(strPath);
        Console.WriteLine("Directory Deleted Successfully");
        Console.ReadKey();
       }
       else
        {
          Console.WriteLine("Directory not exists");
                    Console.ReadKey();
        }
     }
     catch (Exception ex)
     {
     }
 }

I hope this will be helpful for you. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome.

No comments:

Post a Comment

^ Scroll to Top