How to resolve Dynamics CRM Plugin System.Security

2019-03-07 07:09发布

Business Process Error System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) at System.Security.CodeAccessPermission.Demand() at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes, Boolean checkHost) at RetrieveAttachments.RetrieveClass.Execute(IServiceProvider serviceProvider) The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.FileIOPermission The Zone of the assembly that failed was: MyComputer

I also added following method in plugin AssemblyInfo.cs file [assembly: System.Security.AllowPartiallyTrustedCallers] but its raise same error.

QueryExpression notes = new QueryExpression { EntityName = "annotation", ColumnSet = new ColumnSet("filename", "subject", "annotationid", "documentbody","mimetype") };
notes.Criteria.AddCondition("annotationid", ConditionOperator.Equal, annotationid);
     EntityCollection NotesRetrieve = service.RetrieveMultiple(notes);
     if (NotesRetrieve != null && NotesRetrieve.Entities.Count > 0)
     {
      foreach (var note in NotesRetrieve.Entities)
      {
       string fileName = note.GetAttributeValue<string>("filename");
       string cleanFileName = string.Empty;
       foreach (var chr in fileName.ToCharArray().ToList())
       {
        if(!Path.GetInvalidFileNameChars().Contains(chr)) cleanFileName = cleanFileName + chr; 
       }
     FileIOPermission f = new FileIOPermission(FileIOPermissionAccess.Write, @"D:\note");
     string fileLocation = Path.Combine(@"D:\note", cleanFileName);
     byte[] fileContent = Convert.FromBase64String(NotesRetrieve.Entities[0].Attributes["documentbody"].ToString());
     System.IO.File.WriteAllBytes(fileLocation, fileContent);
    }
   }

2条回答
狗以群分
2楼-- · 2019-03-07 07:11

If your plugin is registered in sandbox then this could be the problem. Try to register it outside of the sandbox. Here you can find information about trust levels

查看更多
▲ chillily
3楼-- · 2019-03-07 07:33

Reading file from a sandbox plugin is prohibited. Try to change isolation mode to none.

查看更多
登录 后发表回答