开发者

File access issue

Before writing to the file:

using (StreamWriter outfile = new StreamWriter(filePath, false, System.Text.Encoding.UTF8))
{
    outfile.Write(content);            
}

I'm checking the file write accsses using this:

public bool CheckIfAccessToFileIsGranted(string filePath)
{
     try
     {
        new FileIOPermission(FileIOPermissionAccess.Write, filePath).Demand();
        return true;
     }
     catch (SecurityException)
开发者_开发问答     {
        return false;
     }
}

Despite the fact above function grants me the assess (returns true), I'm getting UnauthorizedAccessException while opening the stream. Why ?

Regards


The problem here is you're confusing Code Access Security (CAS) with File System Permissions. The former is a restriction which applies only to CLR processes while the latter is an operating system level restriction. These two methods of security are independent of each other (although file system information can contribute to CAS policy).

In this case the UnauthorizedAcessException represents a lack of permissions in the file system but you're attempting to guard it with a CAS check which will not work.

At the file system level (excluding CAS) the practice of attempting to verify an operation will or won't succeed before hand is really a futile one. There is simply no way to do this properly because so many outside entities can change the file system between the check and attempt to access. It's much more reliable to just try and access the file and catch the exception which results from the failed access.

Here's a link to a detailed blog post I wrote on this issue

  • http://blogs.msdn.com/b/jaredpar/archive/2009/12/10/the-file-system-is-unpredictable.aspx


Just don't do this. While JaredPar has the right answer for why it's not working in this case, I want to expand on his last sentence: that the entire exercise is futile.

File system permissions are volatile. They can change from one moment to the next in ways that are completely independent from your application code, and this includes the moment in between when you check the permissions and when you try to write to the file. And while permissions don't change all that often, the file could even be deleted or renamed during this critical period.

The point is that, while small, the odds of something happening during that small window are high enough that you need to devote time to building a good exception handler for this code. And once you've done that, all this work you went through to the check the file permissions suddenly becomes moot.

In other words, the correct way to see if you have permission to write to a file is to actually try to write to the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜