C# Tutorial

C# Tutorial C# First Application C# Variables C# Data Types C# Operators C# Keywords

C# Control Statement

C# If Statements C# Switch Statements C# for Loop C# While Loop C# do While loop C# Jump Statements C# Function C# functions with out variable

C# Arrays

C# Arrays

C# Function

C# Function call by value C# Call by reference C# Passing array to function C# Multidimensional Arrays C# Jagged Arrays C# Params C# Array Class C# Command Line Arguments

C# Object Class

C# Object and Classes C# Constructors C# Destructor C# this Keyword C# static field C# static class C# Static Constructor C# Structs C# enum C# Properties

C# Inheritance

C# Inheritance C# Multilevel Inheritance C# Aggregation C# Member overloading C# Method Overriding C# Base

C# Polymorphism

C# Polymorphism C# Sealed

C# Abstraction

C# Abstraction C# Interface

C# Namespace

C# Namespace C# Access Modifiers C# Encapsulation

C# Strings

C# String

C# Misc

C# Design Patterns Dictionary in C# Boxing and Unboxing in C# Ref and Out in C# Serialization in C# Dispose and Finalize in C# CONSOLE LOG IN C# Get File extension in C# Insert query in c# Difference Between List and Dictionary in C# Getters and Setters in C# Extension Methods in C# Insert query in c# CONSOLE LOG IN C# Get File extension in C# Random.NextDouble() Method in C# Binary Search in C# Difference between Delegates and Interfaces in C# Double.IsFinite() Method in C# Index Constructor in C# Abstraction in C# Basic OOPS Concepts In C# Queue.CopyTo() Method in C# single.compareto() method in C# C# Throw Exception in Constructor DECODE IN C# file.setlastwritetimeutc() method in C# Convert Object to List in C# convert.ToSByte(string, IFormatProvider) Method in C# C# Declare Delegate in Interface console.TreatControl C As Input property in C# Copying the queue elements to 1-D Array in C# Array.Constrainedcopy() Method in C# C# in and out Char.IsLetterOrDigit() method in C# Debugging in C# decimal.compare() method in C# Difference between Console.Read and Console.Readline in C# Metadata in C# C# Event Handler Example Default Interface Methods in C# Difference between hashtable and dictionary in C# C# program to implement IDisposable Interface Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File C# Error Logging C# ENCRIPTION Can we create an object for Abstract Class in C# Console.CursorVisible in C# SortedDictionary Implementation in C# C# Hash Table with Examples Setting the Location of the Label in c# Collections in c# Virtual Keyword in C# Reverse of string in C# String and StringBuilder in C# Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File Difference between ref and out in C# Singleton Class in C# Const And Readonly In Csharp BinaryReader and BinaryWriter in C# C# Attributes C# Delegates DirectoryInfo Class in C# Export and Import Excel Data in C# File Class in C# FileInfo Class in C# How to Cancel Parallel Operations in C#? Maximum Degree of Parallelism in C# Parallel Foreach Loop in C# Parallel Invoke in C# StreamReader and StreamWriter in C# TextReader and TextWriter in C# AsQueryable() in C# Basic Database Operations Using C# C# Anonymous Methods C# Events C# Generics C# Indexers C# Multidimensional Indexers C# Multithreading C# New Features C# Overloading of Indexers Difference between delegates and events in C# Operator overloading in C# Filter table in C# C# Queue with Examples C# Sortedlist With Examples C# Stack with Examples C# Unsafe Code File Handling in C# HashSet in C# with Examples List Implementation in C# SortedSet in C# with Examples C# in Depth Delegates and Events in C# Finally Block in C# How to Split String in C# Loggers in C# Nullable Types in C# REVERSE A STRING IN C# TYPE CASTING IN C# What is Generics in C# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# Atomic Methods Thread Safety and Race Conditions in C# Parallel LINQ in C# Design Principles in C# Difference Between Struct And Class In C# Difference between Abstraction and Encapsulation in C# Escape Sequence Characters in C# What is IOC in C# Multiple Catch blocks in C# Appdomain in C# Call back methods in C# Change Datetime format in C# Declare String array in C# Default Access Specifier in c# Foreach in LINQ C# How to compare two lists in C# How to Convert String to Datetime in c# How to get only Date from DateTime in C# Ispostback in asp net C# JSON OBJECT IN C# JSON STRINGIFY IN C# LAMBDA FUNCTION IN C# LINQ Lambda Expression in C# Microservices in C# MSIL IN C# Reference parameter in C# Shadowing(Method hiding) in C# Solid principles in C# Static Members in C# Task run in C# Transaction scope in C# Type Conversion in c# Unit of Work in C# Unit Test Cases in c# User Defined Exception in c# Using Keyword in C# Var Keyword in C# What is gac in C#

DirectoryInfo Class in C#

In C#, the System.IO namespace has the DirectoryInfo class, which offers a method for interacting with file system directories (folders). It is utilized to get directory-related data, manage directory attributes, and conduct operations on directories.

  • The DirectoryInfo class is utilized for file and directory management activities and is a component of the larger.NET Framework and.NET Core libraries.

Properties of DirectoryInfo Class in C#

You may obtain information about a directory (or folder) in the file system with the DirectoryInfo class in the C# language. Here are a few of the DirectoryInfo class's frequently used properties

PropertiesDescription
FullName  Returns the Directory's complete path, which includes its name.
NameRetrieves the Directory's name only, not its path.
ParentGets the current Directory's parent directory using the parent keyword.
ExistsThis value describes whether the Directory is present in the file system.
AttributeGets or modifies the characteristics connected to the Directory. This feature lets you change attributes like read-only, hidden, and more.
RootReturns the directory path's root segment.
extensionGets the associated with the Directory's name. The return value of this field is an empty string because directories don't have extensions.
GetFileSystemInfos()The method provides an array of FileSystemInfo objects that represent the files and directories in the current Directory.

Methods:

The DirectoryInfo class in C# offers several crucial methods for interacting with file system directories. As always, while working with file system operations, handle exceptions properly.

MethodsDescription
createThe DirectoryInfo object's representation of a directory is created using the method. Calling this method with an existing directory has no effect.
DeleteThe Directory is deleted using the method. You can decide whether to destroy everything (including all subdirectories and files) using the optional recursive parameter.
GetFilesAn array of FileInfo objects representing the files in the Directory are returned by the GetFiles() function. You can offer optional file-filtering choices and search patterns.
GetDirectoriesA list of DirectoryInfo objects representing the subdirectories in the Directory is returned by the GetDirectories() function. Search patterns and choices to filter the subdirectories are optional.
MoveTo()The Directory can be relocated using the MoveTo() method. The new route is offered as support. An exception is thrown if the target directory already exists.
EnumerateFiles() and EnumerateDirectories(),These methods return enumerators that let you cycle through files and directories slowly. These methods may be more memory-efficient when dealing with huge directory structures than GetFiles() and GetDirectories().

Example:

We are constructing a T&E directory in the example below by specifying the directory path.

using System;

using System.IO;

namespace DirectoryCreationExample

{

    class Program1

    {

        static void Main(string[] args)

        {

            string directoryPath = @"C:\MyDirectory"; // Provide the desired directory path here

            try

            {

                // Create a DirectoryInfo object

                DirectoryInfo directory = new DirectoryInfo(directory path);

                // Check if the Directory already exists

                if (Directory. Exists)

                {

                    Console.WriteLine("Directory already exists.");

                    return;

                }

                // Create the Directory

                directory.Create();

                Console.WriteLine("The directory has been created successfully.");

            }

            Catch (Exception e)

            {

                Console.WriteLine("Directory not created: " + e.Message);

            }

        }

    }

}

Output:

DirectoryInfo Class in C#
  • Making a DirectoryInfo Object Using the given directory path, a DirectoryInfo object with the name directory is made inside the try block.
  • The program uses the Exists attribute of the DirectoryInfo object to determine whether the Directory already exists.
  • The program terminates if the Directory is present and a notice is displayed.
  • The program invokes the Create method on the DirectoryInfo object to create the Directory if it does not already exist.

Following a directory creation attempt, the program prints the necessary messages to the console indicating whether the Directory was successfully formed.

Example:

 The program shows how to delete a directory using the DirectoryInfo class.

using System;

using System.IO;

namespace DirectoryDeletionExample

{

    class Program2

    {

        static void Main(string[] args)

        {

            string directoryPath = @"C:\T&E"; // Provide the directory path to delete

            try

            {

                // Create a DirectoryInfo object

                DirectoryInfo directory = new DirectoryInfo(directory path);

                // Delete the Directory

                directory.Delete();

                Console.WriteLine("The directory has been deleted successfully.");

            }

            Catch (Exception e)

            {

                Console.WriteLine("Something went wrong: " + e.Message);

            }

        }

    }

}

Output:

DirectoryInfo Class in C#

To deal with any unexpected errors that may occur. Ensure you're running the program in a situation where you can remove directories from the path supplied.

  • Making a DirectoryInfo Object Using the given directory path, a DirectoryInfo object with the name directory is made inside the try block.
  • The program invokes the destroy method on the DirectoryInfo object to destroy the Directory.
  •  Output following a directory deletion attempt, the program sends the proper messages to the console informing the user if the Directory was successfully deleted or if an exception occurred.

Example:

A directory can be moved from one place to another using the DirectoryMethod.

using System;

using System.IO;

class Program3

{

    static void Main(string[] args)

    {

        string sourceDirectory = @"C:\Myfile";

        string destinationDirectory = @"C:\Therefile";

        try

        {

            Directory.Move(sourceDirectory, destinationDirectory);

            Console.WriteLine("Directory moved successfully.");

        }

        Catch (Exception e)

        {

            Console.WriteLine("An error occurred: " + e.Message);

        }

    }

}

Output:

DirectoryInfo Class in C#

The two required parameters are the source and destination directory paths. The Directory is the move method. You can move a directory from one place to another using the Move method.

  • The two required parameters are the source and destination directory path
  • It would be best to replace DestinationDirectory with the path to the final destination andSourceDirectory with the path to the Directory you wish to relocate.
  • The program will attempt to relocate the Directory and display the necessary notifications indicating whether the move was successful or had any problems.
  •  Verify that you have the right permissions to operate on directories in the designated places.

Example:

The DirectoryInfo class from the System.IO namespace can retrieve directory details in C#.

using System;

using System.IO;

class Program

{

    static void Main(string[] args)

    {

        string directoryPath = @"C:\MyFile"; // Provide the directory path

        try

        {

            // Create a DirectoryInfo object

            DirectoryInfo directory info = new DirectoryInfo(directory path);

            // Check if the Directory exists

            if (directory info. Exists)

            {

                Console.WriteLine("Directory Name: " + directoryInfo.Name);

                Console.WriteLine(“Full Path:” + directoryInfo.FullName);

                Console.WriteLine("Creation Time: " + directoryInfo.CreationTime);

                Console.WriteLine("Last Access Time: " + directoryInfo.LastAccessTime);

                Console.WriteLine("Last Write Time: " + directoryInfo.LastWriteTime);

                Console.WriteLine("Attributes:" + directoryInfo.Attributes);

                Console.WriteLine("Parent Directory: " + directoryInfo.Parent);

                Console.WriteLine("Root Directory: " + directoryInfo.Root);

            }

            else

            {

                Console.WriteLine("Directory does not exist.");

            }

        }

        Catch (Exception e)

        {

            Console.WriteLine("An error occurred: " + e.Message);

        }

    }

}

Output:

DirectoryInfo Class in C#
  • This class offers several attributes and methods to get data from a file system directory (folder).
  • The path to the Directory you want to receive details should be substituted for C: Directory.
  • To show various information about the Directory, like its name, full path, creation time, and other facts, the program will create a DirectoryInfo object and utilize its properties.

To access the provided Directory, ensure the program runs with the correct permissions. To deal with potential issues while accessing the file system, adequate exception handling is also advised.

Example:

A subdirectory can be created inside an existing directory represented by a DirectoryInfo object using the CreateSubdirectory function of the DirectoryInfo class.

using System;

using System.IO;

class Program4

{

    static void Main(string[] args)

    {

        string parentDirectory = @"C:\ParentDirectory"; // Provide the parent directory path

        string subdirectoryName = "SubDirectory"; // Specify the subdirectory name

        try

        {

            DirectoryInfo parentInfo = new DirectoryInfo(parentDirectory);

            DirectoryInfo subdirectoryInfo = parentInfo.CreateSubdirectory(subdirectoryName);

            Console.WriteLine("Subdirectory created successfully at: " + subdirectoryInfo.FullName);

        }

        Catch (Exception e)

        {

            Console.WriteLine("An error occurred: " + e.Message);

        }

    }

}

Output:

DirectoryInfo Class in C#
  • In C#, you can use the Directory. The createDirectory or the CreateSubdirectory method of the DirectoryInfo class creates a subfolder inside an existing directory.
  • The Directory's CreateDirectory method. You can create a subdirectory inside an existing directory using the CreateDirectory function.
  •  It accepts as an argument the path to the new subfolder.

Example:

A Sample program retrieves and displays a specified directory's subdirectories using the GetDirectories function from the DirectoryInfo class.

using System;

using System.IO;

class Program5

{

    static void Main(string[] args)

    {

        string parentDirectory = @"C:\ParentDirectory"; // Provide the parent directory path

        try

        {

            DirectoryInfo parentInfo = new DirectoryInfo(parentDirectory);

            if (parentInfo.Exists)

            {

                DirectoryInfo[] subdirectories = parentInfo.GetDirectories();

                if (subdirectories. Length > 0)

                {

                    Console.WriteLine("Subdirectories in " + parentInfo.FullName + ":");

                    for each (var subdirectory in subdirectories)

                    {

                        Console.WriteLine(subdirectory.Name);

                    }

                }

                else

                {

                    Console.WriteLine("No subdirectories found in " + parentInfo.FullName);

                }

            }

            else

            {

                Console.WriteLine("Parent directory does not exist.");

            }

        }

        Catch (Exception e)

        {

            Console.WriteLine("An error occurred: " + e.Message);

        }

    }

}

Output:

DirectoryInfo Class in C#

You can retrieve subdirectories for the directory by entering its path in the format ParentDirectory.

  • Using the Exists attribute of the DirectoryInfo object, the program determines whether they parent directory is present.
  • It utilizes the GetDirectories method to get a array of DirectoryInfo objects representing the subdirectories if the parent directory is present.
  • The program displays a suitable noticed if no subdirectories are discovered.

Any potential exceptions are deal with properly to prevent them from happening again.