Skip to main content

Simulating access denial (ACL)

To simulate Windows access control list (ACL) restrictions, register an IAccessControlStrategy with WithAccessControlStrategy(...).

The built-in DefaultAccessControlStrategy takes a callback (fullPath, extensibility) => bool; return false to deny access to that path. Operations on a denied path then throw UnauthorizedAccessException with the message "Access to the path '{fullPath}' is denied.", like the real Windows file system:

MockFileSystem fileSystem = new();
fileSystem.WithAccessControlStrategy(
new DefaultAccessControlStrategy((path, _) => !path.EndsWith("provenance.txt")));

fileSystem.File.WriteAllText("catalog.json", "[]"); // ok
fileSystem.File.WriteAllText("provenance.txt", ""); // throws UnauthorizedAccessException

A second overload of DefaultAccessControlStrategy additionally receives an AccessRequest, so you can simulate files and directories that can be read but not written, or written but not deleted:

  • Access is the requested FileAccess. Enumerating a directory requests FileAccess.Read. As FileAccess is a flags enum, use HasFlag to also cover FileAccess.ReadWrite.
  • IsDelete is true when the file or directory is deleted. A delete also requests FileAccess.Write.
MockFileSystem fileSystem = new();
fileSystem.File.WriteAllText("catalog.json", "[]");
fileSystem.WithAccessControlStrategy(
new DefaultAccessControlStrategy((path, _, request)
=> !(path.EndsWith("catalog.json") && request.Access.HasFlag(FileAccess.Write))));

fileSystem.File.ReadAllText("catalog.json"); // ok
fileSystem.File.WriteAllText("catalog.json", "[]"); // throws UnauthorizedAccessException

For a custom strategy, derive from the abstract AccessControlStrategy base class instead of implementing IAccessControlStrategy directly, so that it receives the AccessRequest. Implementations of IAccessControlStrategy keep working, but do not receive the request.

Windows-only

WithAccessControlStrategy throws PlatformNotSupportedException on non-Windows hosts (and when simulating a non-Windows OS). ACL functionality is intentionally tied to Windows behavior.

Reading and writing ACL objects​

This page is about denying access. To read and write FileSecurity / DirectorySecurity objects (the GetAccessControl / SetAccessControl APIs), install the Testably.Abstractions.AccessControl companion package.