DirectoryInfo.Exists always returns false during M

2019-02-25 07:51发布

问题:

I have a little bit of logic at the boundary of my app dealing with creating directories. I would like to test that it actually creates directories as expected, but the DirectoryInfo.Exists property always returns false even when the directory actually exists.

See also this question - you need to set a breakpoint to see that the directory has actually been created because MSTest will delete it when the test ends.

Is there some setting that tells MSTest to allow "normal" filesystem IO during tests?

回答1:

Assuming you create the DirectoryInfo instance somewhat earlier there is some internal caching of directory state involved - if you call DirectoryInfo.Refresh() to force an update this should work:

var dir = new DirectoryInfo(@".\someDir");
//...other things here
dir.Refresh();
bool doesExist = dir.Exists;