How to check for directory write permission in .NET when 'Controlled folder access' ON

457 Views Asked by At

When trying to create folder in My Documents with 'Controlled folder access' ON CreateFolder throws FileNotFoundException. I need to check if my app can create folder in My Documents. How I can check that I have permission for it when 'Controlled folder access' ON.

I tried DirectoryInfo.GetAccessControl method for it, it shows that it allows. Is only way now for me to try create a folder and handle FileNotFoundException.

try
{
    Directory.CreateDirectory(Path.Combine(MyDocuments, "Foo"));
}
catch (FileNotFoundException)
{
    //Do something
}
2

There are 2 best solutions below

0
On

The best way to deal with this is by checking a couple of things.

  1. Check whether Controlled folder access is enabled on the computer
  2. If it is enabled then check to see if your application has been exempted from the control.

This is done by checking the local machine registry key:

HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Windows Defender Exploit Guard\Controlled Folder Access

  1. Read the value for EnableControlledFolderAccess (1 is enabled 0 for disabled) - note that this can also be nothing!
  2. Loop through the SubKeyNames then GetValueNames() for the key AllowedApplications - (returns a string array)

If Controlled Folder Access is enabled and your application name (Assembly.GetExecutingAssembly().ManifestModule.Name) is not in the AllowedApplications list, then you'll get the FileNotFoundException and won't be able to create the folder (the user will also get a virus warning!).

EDIT:

There is also another subkey under that hive, ProtectedFolders which lists the default folders that Microsoft have decided need to be protected (and include folders such as My Documents, My Pictures etc) plus any others that the user (administrator) may add. You could also check this (string array) if Controlled Folder Access is enabled on the system.

2
On

The FileNotFoundException is certainly unexpected here as Directory.CreateDirectory does not have it in the list of documented exceptions. This exception seems to be the result of Windows Defender blocking your app from accessing the folder and not the Windows File System which is on the lower level and hence the System.IO is giving you a successful result.

Check this thread as it seems to be your situation. And the very last comment is suggesting to allow the app via Controlled access list. I suspect until the proper exception type is implemented low level you are pretty much stuck catching the undocumented exception here. There might be some undocumented WinAPI to ask the Windows Defender if your app has access to the folder, but relying on it might be more error prone in the long run. Hope it helps!