When your code does the following:
You run the risk that the permissions change between 1 and 2 because you can't predict what else will be happening on the system at runtime. Therefore, your code should handle the situation where an UnauthorisedAccessException is thrown even if you have previously checked permissions.
Note that the SecurityManager class is used to check CAS permissions and doesn't actually check with the OS whether the current user has write access to the specified location (through ACLs and ACEs). As such, IsGranted will always return true for locally running applications.
Example (derived from Josh's example):
//1. Provide early notification that the user does not have permission to write.
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if(!SecurityManager.IsGranted(writePermission))
{
//No permission.
//Either throw an exception so this can be handled by a calling function
//or inform the user that they do not have permission to write to the folder and return.
}
//2. Attempt the action but handle permission changes.
try
{
using (FileStream fstream = new FileStream(filename, FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
writer.WriteLine("sometext");
}
}
catch (UnauthorizedAccessException ex)
{
//No permission.
//Either throw an exception so this can be handled by a calling function
//or inform the user that they do not have permission to write to the folder and return.
}
It's tricky and not recommended to try to programatically calculate the effective permissions from the folder based on the raw ACLs (which are all that are available through the System.Security.AccessControl classes). Other answers on Stack Overflow and the wider web recommend trying to carry out the action to know whether permission is allowed. This post sums up what's required to implement the permission calculation and should be enough to put you off from doing this.