C# - How to Check If a Directory Exists Using DirectoryInfo.Exists?

Learn, how to check if a directory exists using DirectoryInfo.Exists using C# program?
Submitted by IncludeHelp, on November 16, 2017 [Last updated : March 26, 2023]

Check If a Directory Exists

To check if a directory exists or not in C#, we use DirectoryInfo.Exists property.

DirectoryInfo.Exists

This is a method of "DirectoryInfo" class, it is used to check whether a directory exists on or not.

Syntax

bool DirectoryInfo.Exists

Parameter(s)

  1. None

Return Value

Returns the Boolean value true/false.

C# program to check if a directory exists using DirectoryInfo.Exists

using System;
using System.IO;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      DirectoryInfo d = new DirectoryInfo("mydir");

      if (d.Exists)
        Console.WriteLine("Directory exists");
      else
        Console.WriteLine("Directory does not exists");
    }
  }
}

Output

Directory exists

Explanation

In this program, we create an object of DirectoryInfo class and initialize with a directory-name, then check directory exists or not using Exists property of DirectoryInfo class.

Note: In above program, we need to remember, when we use "DirectoryInfo" class, System.IO namespace must be included in the program.

C#.Net DirectoryInfo Class Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.