Sagar0921 Sagar0921 - 3 months ago 9
C# Question

Delete path that is longer than 256 characters using DirectoryInfo.Delete(true) method in c#

My Goal is to use Delete the entire folder and everything inside of that folder that is older than month. Following is code that i wrote:

foreach (String dir in Directory.EnumerateDirectories(args[0]))
{
foreach (String subDir in Directory.EnumerateDirectories(dir))
{
DirectoryInfo dirInfo = new DirectoryInfo(subDir);
if (dirInfo.CreationTime < DateTime.Today.AddMonths(-1))
{
try
{
dirInfo.Delete(true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}


Isssue: dirInfo.Delete(true) statement throws an exception when path is longer than 256 characters, and does not delete the folder. How can i over come that?
Thank you

Answer

You could try moving the folder first to a shorter directory path first so its path is no longer as long, and then deleting it.

dirInfo.MoveTo("C:\temp");
dirInfo.Delete(true);