C# Program To Demonstrate The Use Of The Createsubdirectory Method

In this guide, we will explore a C# code example demonstrating the functionality of the CreateSubdirectory method in C#. Prior to delving into its practical application, it is essential to understand the purpose and behavior of the CreateSubdirectory method.

What is the CreateSubdirectory method?

In the .NET Framework, the C# Directory class provides static functions for generating subdirectories and additional directories, along with functionalities for duplicating, relocating, and removing them. Prior to utilizing the Directory class, it's essential to include the System.IO namespace. The DirectoryInfo class, belonging to the System.IO namespace, is employed for the creation, deletion, and relocation of directories, offering various methods to perform actions on directories and their subdirectories.

The DirectoryInfo class includes various methods for executing diverse tasks. Within this class, you can find the CreateSubdirectory method designed specifically for generating subdirectories. In this example, the illustrated method pertains to the DirectoryInfo class.

Syntax:

It has the following syntax:

Example

public System.IO.DirectoryInfo CreateSubDirectory(String source_path);

Here, source_path refers to the specified path.

Output: The function will provide the final directory in the specified path.

Exception:

An ArgumentException is thrown when the source_path either does not contain a valid file path or includes an invalid DirectoryInfo.

If the provided source path is null, it will result in an ArgumentNullException being raised.

DirectoryNotFoundException occurs when an invalid path is provided.

An IOException occurs when the subdirectory fails to be created.

The PathTooLongException occurs when the provided path, file name, or both surpass a predefined maximum length set by the system.

If the calling function lacks authorization to access the code, a SecurityException is thrown.

The NotSupportedException is thrown when the path contains a semicolon, which is not a valid part of the designated drive label such as "E:\".

Example:

Let's consider a program to execute the CreateSubdirectory function in C#.

Example

using System; 
using System.IO; 

class CreateSubDirectory{ 

	static void Main() 
	{ 

		// getting the specified directory
		DirectoryInfo main_dir = new DirectoryInfo("Programs"); 

		// The subdirectory named "C#_Programs is 
		//created under the Programs directory"
		main_dir.CreateSubdirectory("C#_Programs"); 

		Console.WriteLine("C#_Programs subdirectory is created successfully."); 
	} 
}

Output:

Output

C#_Programs subdirectory is created successfully.

Input Required

This code uses input(). Please provide values below: