Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 543
jwaliszko Avatar asked Apr 28 '26 11:04

jwaliszko


1 Answers

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
like image 172
JaredPar Avatar answered Apr 30 '26 23:04

JaredPar