C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# DirectoryInfo ClassDirectoryInfo class is a part of System.IO namespace. It is used to create, delete and move directory. It provides methods to perform operations related to directory and subdirectory. It is a sealed class so, we cannot inherit it. The DirectoryInfo class provides constructors, methods and properties that are listed below. C# DirectoryInfo Syntax[SerializableAttribute] [ComVisibleAttribute(true)] public sealed class DirectoryInfo : FileSystemInfo C# DirectoryInfo ConstructorsThe following table contains the constructors for the DirectoryInfo class.
C# DirectoryInfo PropertiesThe following table contains the properties of the DirectoryInfo class.
C# DirectoryInfo MethodsThe following table contains the methods of the DirectoryInfo class.
C# DirectoryInfo ExampleIn the following example, we are creating a TheDeveloperBlog directory by specifying the directory path.
using System;
using System.IO;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
// Provide directory name with complete location.
DirectoryInfo directory = new DirectoryInfo(@"F:\TheDeveloperBlog");
try
{
// Check, directory exist or not.
if (directory.Exists)
{
Console.WriteLine("Directory already exist.");
return;
}
// Creating a new directory.
directory.Create();
Console.WriteLine("The directory is created successfully.");
}
catch (Exception e)
{
Console.WriteLine("Directory not created: {0}", e.ToString());
}
}
}
}
Output: The directory is created successfully. In below screenshot, we can see that a directory is created.
The DirectoryInfo class also provides a delete method to delete created directory. In the following program, we are deleting a directory that we created in previous program. C# DirectoryInfo Example: Deleting Directory
using System;
using System.IO;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
// Providing directory name with complete location.
DirectoryInfo directory = new DirectoryInfo(@"F:\TheDeveloperBlog");
try
{
// Deleting directory
directory.Delete();
Console.WriteLine("The directory is deleted successfully.");
}
catch (Exception e)
{
Console.WriteLine("Something went wrong: {0}", e.ToString());
}
}
}
}
Output: The directory is deleted successfully. It throws a System.IO.DirectoryNotFoundException exception if the specified directory not present at the location.
Next TopicC# Serialization
|