简体   繁体   English

在C#/ Windows中模拟文件的“拒绝访问”

[英]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. 我正在尝试为小型C#例程编写集成测试,该例程读取不同的文件。

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: 我怀疑这可以使用DirectorySecurity,进行模拟DirectorySecurity,但是,我不确定是否可以在所有情况下正确执行:

    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). 例如,假设我可以剥离正在运行测试的当前用户的访问规则(这也需要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). 我可能可以使用Moles或任何其他基于模拟的方法来做到这一点,但我对一般解决方案更感兴趣(例如,为本机应用程序重用此测试)。

What am I missing? 我错过了什么? Any simple way to do this? 有什么简单的方法吗?

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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