Home > Tutorial for Beginners > Directory Classes Tutorial in C#

Directory Classes Tutorial in C#

Applicable for C#: 1.0, 1.1, 2.0, 3.0, 3.5, 4.0

Directory classes are very important when user want to save information in a file instead of database. Directory works as a folder which contains multiple files like windows folders. In .Net by using System.IO namespace we can do all operation related with directory manipulation such as creating new directory, deleting the content of existing directory, you can rename existing directory or file and many more. Here are the list of few common properties and methods

Property

  • Root: It is used to retrieve the root of a path
  • Parent: By using this you can get name of the parent directory of any subdirectory
  • Exists: It is used to check whether a directory is exist or not
  • IsDirectory: It is used to check the object is directory
  • IsFile: It is used to check the object is file.
  • Attributes: It is used to set/get the attributes of file such as read only, hidden.

Method

  • GetCurrentDirectory (): Is used to display the path of current directory
  • CreateFile (): It is used to create a file. Here you have to define the path with permission.
  • Delete (): It is used to delete a directory and its contents.
  • GetFiles (): It is used to get all files from a directory.
  • MoveTo (): It helps us to move a directory to a new path along with contents.
  • CreateSubdirectory (): It is used to create the subdirectory of the selected/specified directory.

Example:

ListBox1.Items.Add(“Current Directory”);

        ListBox1.Items.Add(Directory.GetCurrentDirectory());

        ListBox1.Items.Add(“Check File”);

            

        if(File.Exists(@”c:\test.txt”))

        {

            ListBox1.Items.Add(“File Already exists at C:\test.txt”);

        }

        else

        {

            ListBox1.Items.Add(“New file Create at C:\test.txt, Please check”);

            File.Create (@”C:\test.txt”);

        }

 

        if (Directory.Exists(@”C:\demo”))

        {

            Directory.Delete(@”C:\demo”);

            ListBox1.Items.Add(“Directory Deleted”);

        }

 

        else

        {

            ListBox1.Items.Add(“Invalid Path”);

        }

 

        ListBox1.Items.Add(“Get All Files”);

        string[] str = Directory.GetFiles(@”d:\Personal\Books\”);

 

        for (int i = 0; i < str.Length; i++)

        {

            ListBox1.Items.Add(str[i].ToString());

        }

 

Output:

Directory Classes Tutorial Code in C#

Post Comments Below

  1. No comments yet.
  1. No trackbacks yet.