Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't a DirectoryInfo instance (re)create a folder after deleting it?

I'm assuming .NET DirectoryInfo and FileInfo objects are similar to Java's java.io.File, i.e. they represent abstract paths and aren't necessarily connected to existing physical paths.

I can do what I'm trying to do (empty out a folder and create it if it doesn't exist) in a different way that works, but I'd like to understand why this does not:

using System.IO;

namespace TestWipeFolder
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var di = new DirectoryInfo(@"C:\foo\bar\baz");

            if (di.Exists)
            {
                di.Delete(true);
            }

            // This doesn't work.  C:\foo\bar is still there but it doesn't remake baz.
            di.Create();
        }
    }
}

UPDATE: I tried the same code after a reboot and it worked fine. I still want to know what the similarities are to Java File objects and whether deleting a folder a DirectoryInfo object references can screw things up, but that is on the back burner now.

like image 579
Dan Novak Avatar asked Sep 30 '22 02:09

Dan Novak


1 Answers

The DirectoryInfo class provides you the information of a directory at the time you create the DirectoryInfo instance.

If changes are made to the directory like delete, then the information is not reflected to your current instance. You need to call .Refresh() on the instance to update the state of the DirectoryInfo instance.

LinqPad Testcode:

var di = new DirectoryInfo(@"C:\foo\bar\baz");
di.Dump();

if (di.Exists){
  di.Exists.Dump();  // prints out true

  di.Delete(true);
  di.Exists.Dump();  // still prints out true

  di.Refresh();
  di.Exists.Dump();    // prints out false
}

di.Create();
di.Refresh();
di.Exists.Dump();    // prints out true

The similar classes to the java ones are System.IO.File and System.IO.Directory. Using this classes you will get the current state of the files and directories.

like image 100
Jehof Avatar answered Oct 18 '22 23:10

Jehof