简体   繁体   中英

Directory.Exists returns true when directory is not present

I am working on an application for Windows 7, and run some routine directory creation code:

string dirPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MyDir");    
if (!Directory.Exists(dirPath))
   Directory.CreateDirectory(dirPath);

The problem is that the Directory.Exists line returns true, when I can't see the directory through command line and Windows Explorer. This isn't an issue when working with Windows XP. Is there something going on with Windows 7 that I'm not aware of?

EDIT: Added Path.Combine

Please understand that Windows Vista and Windows 7 use virtualization to protect such folders, so you need to check if myDir is in virtualstore,

C:\\Users(user name)\\AppData\\Local\\VirtualStore\\ProgramData

I don't know why Windows 7 is doing that, and I don't have a copy to test, but your check to Directory.Exists(path) shouldn't be necessary. If you reflect (deep) into Directory.CreateDirectory(path), you'll find that it internally checks to see if the directory already exists, and it's not a problem to call it multiple times on a directory that already exists. The call to Directory.Exists(path) is extraneous and unnecessary.

Of course, if Windows 7 isn't doing the Directory.Exists the way I'd expect, maybe it doesn't do the naked Directory.CreateDirectory either. In any case, it's worth testing.

CommonApplicationData typically resolves to <OSDrive>\\ProgramData on Windows 7. This is a hidden folder. If you don't ask Explorer to show hidden files and folders (from the Folder Options->View UI), you won't see it in Explorer.

EDIT : Make sure you're viewing the correct directory in Explorer: browse to %PROGRAMDATA% , not C:\\ProgramData.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM