How to delete folder in CSharp

In this example we will see how to delete folder or directory using C#.

The Directory.Delete() method will delete directory or subdirectory at specified path.

Try it
 
			string folderPath = @"C:\Test\Dir1";
			if (Directory.Exists(folderPath))
			{
				Directory.Delete(folderPath);
			}
		

A directory that contains files or folders can't be deleted hence we need to make sure that given directory is empty else it will throw an error. So lets see how to delete all the files and folder from specific directory.

Try it
 
			string folderPath = @"C:\Test";
			DeleteDirectory(folderPath);
	
			private void DeleteDirectory(string folderPath)
			{
				if (Directory.Exists(folderPath))
				{
					foreach (string filePath in Directory.GetFiles(folderPath))
					{
						File.Delete(filePath);
					}
		
					foreach (string subDir in Directory.GetDirectories(folderPath))
					{
						DeleteDirectory(subDir);
					}
		
					Directory.Delete(folderPath);
				}
			}
		

In the above code we have made recursive function to delete all the directories at n level. So it will check each folder for files and folder.