views:

259

answers:

1

I have read over the documentation, scoured the interwebs, and it seems what I want to do cannot be done without writing a custom CAS permission. So, here's my last ditch attempt.

I want to DECLARATIVELY define a FileIOPermission (Attribute) on my class to demand permission to the users MyDocuments directory. This directory is not consistent on all operating systems, and is generally accessed in .net through Path.GetFolderPath (I think thats it), passing a SpecialFolder enum value. Is there any 'token' syntax, or similar feature in the FileIOPermissionAttribute to say to the runtime - 'give me access to this SpecialFolder, wherever it may be on this system'?

If not I guess I'll have to write a custom Permission object which does essentially that...

Thanks!

+1  A: 

You don't actually need a custom permission for this, but you do need a custom attribute that resembles FileIOPermissionAttribute. In its CreatePermission method, you can create a FileIOPermission for the actual folder path corresponding to SpecialFolder value passed to the attribute. e.g. (that needs some validation added):

[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
public sealed class SpecialFolderIOPermissionAttribute : CodeAccessSecurityAttribute
{
 private Environment.SpecialFolder _folder;
 private FileIOPermissionAccess _access;

 public SpecialFolderIOPermissionAttribute(SecurityAction action)
  : base(action)
 {
  this.Unrestricted = true;
 }

 public Environment.SpecialFolder Folder
 {
  get
  {
   return this._folder;
  }
  set
  {
   this._folder = value;
   this.Unrestricted = false;
  }
 }

 public FileIOPermissionAccess Access
 {
  get
  {
   return this._access;
  }
  set
  {
   this._access = value;
   this.Unrestricted = false;
  }
 }

 public override IPermission CreatePermission()
 {
  FileIOPermission permission;
  if (this.Unrestricted)
  {
   permission = new FileIOPermission(PermissionState.Unrestricted);
  }
  else
  {
   permission = new FileIOPermission(this.Access, Environment.GetFolderPath(this.Folder));
  }

  return permission;
 }
}

One thing to watch out for here is that Environment.GetFolderPath will make a demand for PathDiscovery access on the target folder, so you'll have to decide if you want to assert that permission in your CreatePermission method. (Personally, I suspect that the complications around this may be one of the reasons that the BCL team didn't implement special folder support in FileIOPermissionAttribute in the first place.)

Nicole Calinoiu