How to check file directory exists, remove it if does else create it using C# (.NET)

They're times when you need to find out if a Directory Exists on the hard disk then Create it if it doesn't or Remove it. You can do it using a batch file before running a program, but it'll be a lot easier if the program that was to be run could do it.

.NET Libraries have a whole library that will handle file operations, so you don't have to call any Windows API library calls. The library is intuitively called the IO library, and to reference it, you add the following using statement at the top of the code.

using System.IO;

You can then use the following snippets to do the appropriate action.

How to check if folder exists

if(Directory.Exists("c:\\temp\\folder"))
{
}

For the above example, you put in the necessary code you want to execute inside the brackets. Remember, it's C#, so for folder separators, you will need a double slash to equal a single slash unless you type in the value whilst the code runs. Then, you will need a single slash as it's stored in a variable.

How to delete a folder

Directory.Delete("C:\\temp\\Folder",true);

The above command will delete the named folder. If you provide a true value, an optional parameter, then it will try to delete any files or directories inside the folder you want to delete. If any file has the read-only bit set, it will error, and you can't delete the folder. If the fourth file in ten files is write-protected, then the first three files will be deleted, but it will stop.

An exception will occur if the folder doesn't exist. You should combine this statement with the folder's first example so that no error occurs.

How to create a folder

Directory.CreateDirectory("C:\\temp\\folder");

The above will create a folder on the disk. If the folder already exists, then there will be an error. It would help if you combined this with the first example to prevent the code from generating an error.

Tags - .NET

Last Modified : June 2023


About... / Contact.. / Cookie...