Why does a DirectoryInfo (re) instance not create a folder after deleting it?

I assume that the .NET DirectoryInfo and FileInfo objects are similar to Java java.io.File, i.e. represent abstract paths and are not necessarily related to existing physical paths.

I can do what I am trying to do (free the folder and create it if it does not exist) in a different way, but I would like to understand why it is 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 reboot and it worked fine. I still want to know what the similarity with Java File objects is and whether the directory removes links to DirectoryInfo objects, but this is already in the background.

+5
source share
1 answer

The DirectoryInfo class provides you with directory information at the time the DirectoryInfo instance is created.

If changes are made to the directory, such as delete, the information will not be displayed in your current instance. You need to call .Refresh() on the instance to update the state of the DirectoryInfo instance.

LinqPad Test Code:

 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 

Similar classes for java are System.IO.File and System.IO.Directory . Using these classes, you will get the current state of files and directories.

+4
source

Source: https://habr.com/ru/post/1200283/


All Articles