2

I want to delete a Directory and all its files and it has files/Directories with a very long path.

The file I'm trying to delete has a long path (longer than 260 characters).

How can I delete this file in spite of its length? I'm using the following code:

foreach (string archiveFolder in Archives)
{
    try
    {
        DateTime creationTime = Directory.GetCreationTime(archiveFolder);
        DateTime now = DateTime.Now;
        DateTime passDate = creationTime.AddDays(numDaysBack);
        if (passDate.CompareTo(now) < 0)
        {
            try
            {
                Directory.Delete(archiveFolder, true);
            }
            catch (Exception e)
            {
            }
            //System.Console.WriteLine(creationTime);

        }
    }
    catch (Exception e)
    {
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
mary
  • 869
  • 5
  • 13
  • 26
  • 3
    Managed code can't deal with paths longer than 260 AFAIK... IIRC the only option would be to call native Windows API via pinvoke... – Yahia Nov 15 '12 at 15:44
  • Also, is this your real code? If so, then you shouldn't be ignoring exceptions. You'd do better to just remove the try/catch blocks entirely. – John Saunders Nov 15 '12 at 15:45
  • 1
    [Why does the 260 character path length limit exist in Windows?](http://stackoverflow.com/questions/1880321/why-does-the-260-character-path-length-limit-exist-in-windows) contains useful information – emartel Nov 15 '12 at 15:46
  • Possible duplicate of http://stackoverflow.com/questions/2223007/c-sharp-deleting-a-folder-that-has-long-paths – Cinchoo Nov 15 '12 at 18:40
  • Is it the target directory's name that's too long or the hole path ? Can you edit your question and add an example of `archiveFolder` ? – Fourat Oct 28 '20 at 07:29
  • Does this answer your question? [C# deleting a folder that has long paths](https://stackoverflow.com/questions/2223007/c-sharp-deleting-a-folder-that-has-long-paths) – Wai Ha Lee Oct 28 '20 at 09:45

2 Answers2

2

I fixed the problem of having a file with long path down inside the directory structure of the directory I'm deleting by prepending \\?\ (long path specifier) to the Directory.Delete argument.

So in your cause it would be

   Directory.Delete(@"\\?\" + archiveFolder, true);
Mikhail
  • 1,223
  • 14
  • 25
  • For the record, it appears this results in an exception about invalid characters in the path, at least on .NET Framework 4.8 – TheXenocide May 02 '23 at 14:12
1

Directory.Delete is meant to delete directories, to delete files use File.Delete

They both reside in System.IO, the change should be trivial.

emartel
  • 7,712
  • 1
  • 30
  • 58
  • I want to delete a Directory and all its files and it has files/Directories with a very long path – mary Nov 15 '12 at 15:42