Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating 'access denied' for a file in C# / Windows

I'm attempting to write integration tests for a small C# routine, which reads different files.

And, well, I accidentally thought that it would be great to have a test, which specifies the behavior for the case when the access to that file is denied.

Does anyone know a nice and simple way to simulate that in the test sandbox?


  • I suspect that this could be emulated using the DirectorySecurity, however, I'm not really sure if it's possible to do it correctly for all cases:

    Assume that, for example, I can strip access rules for the current user, which is running the tests (and this would also require UAC / Elevation).

    I guess in this case I'd lose the ability to restore these rights and dispose my sandbox correctly after the test is finished (without diving into stuff like impersonation and access token manipulations).

  • I probably could do this with Moles or any other mock-based approach, but I'm more interested in a general solution (for example, to reuse this test for a native application).

What am I missing? Any simple way to do this?

like image 612
Yippie-Ki-Yay Avatar asked Sep 15 '25 00:09

Yippie-Ki-Yay


1 Answers

You don't specifically say that you want to acheive this via security settings, so instead, why not get exclusive access to the file somewhere else?

using(File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
    //hold here to keep file locked
}
like image 166
spender Avatar answered Sep 17 '25 13:09

spender