Koo SengSeng
Koo SengSeng

Reputation: 953

How convert List to DirectoryInfo

In my application, I have a specific directory like "C:\Temp\Folder1", imagine this directory has the following sub directories:

C:\Temp\Folder1\Admin\Billy
C:\Temp\Folder1\Customer\Michael
C:\Temp\Folder1\Admin\Julian
C:\Temp\Folder1\Customer\May
C:\Temp\Folder1\Admin\Sebastian

I use DirectoryInfo.GetDirectories() to get all above sub directories and convert into a list to filter out folders with C:\Temp\Folder1\Admin\ and I'm manage to do that. So only "Customer" folder will be remain in the DirectoryInfo variable.

Imagine my list has the following item only:

C:\Temp\Folder1\Customer\Michael
C:\Temp\Folder1\Customer\May

But now i have one problem, I need to delete the Customer folders that are available in the DirectoryInfo variable but the filtered records is a list, not a DirectoryInfo class so I couldn't use the DirectoryInfo.Delete() to delete each Customer folder.

So how do I convert the list to DirectoryInfo or manually add each item in the list into DirectoryInfo so that I can perform deletion on each Customer folder?

Upvotes: 0

Views: 1185

Answers (2)

Phil
Phil

Reputation: 84

You should check out the System.IO.Directory.Delete(string path) method. This would not require creating a new object just to delete the folder.

Upvotes: 0

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

how do I convert the list to DirectoryInfo or manually add each item in the list into DirectoryInfo so that I can perform deletion on each Customer folder?

You can project each element using Enumerable.Select and create a DirectoryInfo from each one:

foreach (var directory in listOfPaths.Select(path => new DirectoryInfo(path))
{
    directory.Delete();
}

Upvotes: 1

Related Questions