Code to Delete Single Sub Folder in .NET Core With C#.Net
To remove a single sub folder first we need to check that the specific fub folder exists in the parent folder or not. If it exists on that case delete the folder. Please check the below code.
//parent directory path
string parentDirectoryPath = "D:\\DemoRepo\\Myfolder";
string deleteDirectoryName = "2";
if (Directory.Exists(parentDirectoryPath))
{
string subDirPath = string.Format("{0}\\{1}", parentDirectoryPath, deleteDirectoryName);
//Get List of all directorys
List<string> subDirecoryList = new List<string>();
subDirecoryList = Directory.GetDirectories(parentDirectoryPath).ToList();
//Validate directory exists
bool directoryStatus = (from d in subDirecoryList
where d == subDirPath
select d).Any();
if (directoryStatus)
{
Directory.Delete(subDirPath, true);
Console.WriteLine("Directory deleted successfully.");
}
else
{
Console.WriteLine("Directory not found.");
}
}
In above code first I have stored the path of the parent directory. Now I have taken a variable where I am defining the directory name which I want to delete, here if you are using in an application, you can dynamically pass the folder name to delete. After defining the variables, I have validated whether the parent folder exists or not. If folder exists on that case i have prepared the path for the subdirectory.
List<string> subDirecoryList = new List<string>();
subDirecoryList = Directory.GetDirectories(parentDirectoryPath).ToList();
//Validate directory exists
bool directoryStatus = (from d in subDirecoryList
where d == subDirPath
select d).Any();
if (directoryStatus)
{
Directory.Delete(subDirPath, true);
Console.WriteLine("Directory deleted successfully.");
}
else
{
Console.WriteLine("Directory not found.");
}
Now check the parent folder. Now we are having only 2 sub directories.
Code to Delete All Sub Folder in .NET Core with C#.Net
string parentDirectoryPath = "D:\\DemoRepo\\Myfolder";
if (Directory.Exists(parentDirectoryPath))
{
//Get List of all sub directorys
var subDirecoryList = Directory.GetDirectories(parentDirectoryPath).ToList();
foreach (var sub in subDirecoryList)
{
if (Directory.Exists(sub))
{
Directory.Delete(sub, true);
}
}
Console.WriteLine(string.Format("Directory '{0}' deleted successfully.", +subDirecoryList.Count()));
}
Now let's understand the above piece of code. Here first I have taken the parent directory folder path. In current time parent directory holding two sub directories. folder 1 and 3. Now to validate the parent directory exists or not I have used Directory.Exists(-). If it exists on that case, it will proceed further. Please check the below code. var subDirecoryList = Directory.GetDirectories(parentDirectoryPath).ToList();
foreach (var sub in subDirecoryList)
{
if (Directory.Exists(sub))
{
Directory.Delete(sub, true);
}
}