實際上您並不需要自定義權限,但您確實需要一個類似於FileIOPermissionAttribute的自定義屬性。在其CreatePermission方法中,您可以爲傳遞給該屬性的SpecialFolder值所對應的實際文件夾路徑創建FileIOPermission。例如(需要一些驗證補充):
[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;
}
}
有一點要注意這裏是Environment.GetFolderPath將使目標文件夾PathDiscovery訪問的需求,所以你必須決定是否要在您的CreatePermission方法中聲明該權限。 (就我個人而言,我懷疑這可能是BCL團隊沒有在FileIOPermissionAttribute中首先實現特殊文件夾支持的原因之一。)