Mohanapriya R Mohanapriya R
Updated date May 08, 2024
In this article, we will learn how to convert strings into directories using C#.

Convert Strings to Directory in C#

In C#, the System.IO namespace provides classes like Directory that enable working with directories. We will be using the Directory.CreateDirectory method, which creates all directories in the specified path if they do not already exist.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Input string representing the directory path
        string directoryPath = "C:\\MyProject\\Files\\Logs";

        // Converting string to directory
        ConvertStringToDirectory(directoryPath);

        Console.WriteLine("Directory created successfully.");
    }

    static void ConvertStringToDirectory(string path)
    {
        // Using Directory.CreateDirectory to create directories
        Directory.CreateDirectory(path);
    }
}

We declare a string variable directoryPath representing the desired directory path. The ConvertStringToDirectory method is then called with this path, using Directory.CreateDirectory to create the specified directory.

Output:

After running the program, you should see the following output:

Directory created successfully.

Upon checking the disk, you will find that the specified directory path ("C:\MyProject\Files\Logs") has been created, including any intermediate directories that did not exist previously.

Comments (0)

There are no comments. Be the first to comment!!!