@T.Zacks , Welcome to Microsoft Q&A,
1) how to get file path with in try block to delete?
You could try the following code to get the file path and directory path by using DirectoryInfo.GetFiles and DirectoryInfo.GetDirectories method.
Also, We could use Directory.Delete method to delete the directory in the list.
List<Task> tasks =
(from c in yourDirList
select new Action(() =>
{
try
{
DirectoryInfo di = new DirectoryInfo(c);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
// do it
Directory.Delete(c);
}
catch (Exception e)
{
// log it
}
})
into action
select Task.Factory.StartNew(action)).ToList();
2) below fragment of code is not clear....please help me to understand.
First, the code will select new Action
create an Action delegate in every loop, we could use into action
store every Action delegate into action.
Second, the code Task.Factory.StartNew(action)) will create a Task based on the action.
Finally, select keyword and Tolist() method will return a Task list.
The next is my completed code, which could delete all the files and directories in the yourDirList.
static void Main(string[] args)
{
var yourDirList= new List<string>();
yourDirList.Add(@"C:\Users\username\Desktop\Test1");
yourDirList.Add(@"C:\Users\username\Desktop\Test2");
yourDirList.Add(@"C:\Users\username\Desktop\Test3");
List<Task> tasks =
(from c in yourDirList
select new Action(() =>
{
try
{
DirectoryInfo di = new DirectoryInfo(c);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
// do it
Directory.Delete(c);
}
catch (Exception e)
{
// log it
}
})
into action
select Task.Factory.StartNew(action)).ToList();
tasks.ForEach(c => c.Wait());
}
Hope my explanation could be helpful.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.