Had an interesting moment this week where we were uploading files to an email without issue, but if you were to open up the attachments they’d be completely blank even though the size of the file was as expected. The actual file contents weren’t being uploaded properly.
The requirement is to attach a file to an email, without saving the attachment anywhere. So… This works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// Add the Attachment(s) from above if (files != null && files.Count() > 0) { foreach (var x in files) { if (x != null) { if (x.ContentLength > 0) { iAttachment += 1; Guid attachmentId = new Guid(); Entity attachmentEntity = new Entity("activitymimeattachment"); attachmentEntity.Attributes["objectid"] = new EntityReference("email", emailId); attachmentEntity.Attributes["filename"] = x.FileName; attachmentEntity.Attributes["objecttypecode"] = "email"; attachmentEntity.Attributes["attachmentnumber"] = 1; attachmentEntity.Attributes["mimetype"] = x.ContentType; byte[] fileData = null; using (var binaryReader = new BinaryReader(x.InputStream)) { //If we don't set this to 0, every item in the array has a 0 byte value. binaryReader.BaseStream.Position = 0; fileData = binaryReader.ReadBytes(x.ContentLength); } attachmentEntity.Attributes["body"] = System.Convert.ToBase64String(fileData); // Create the Attachment in CRM. attachmentId = _service.Create(attachmentEntity); } } } } |
The original code was below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Add the Attachment(s) from above if (files != null && files.Count() > 0) { foreach (var x in files) { if (x != null) { iAttachment += 1; Guid attachmentId = new Guid(); Entity attachmentEntity = new Entity("activitymimeattachment"); attachmentEntity.Attributes["objectid"] = new EntityReference("email", emailId); attachmentEntity.Attributes["filename"] = x.FileName; attachmentEntity.Attributes["objecttypecode"] = "email"; attachmentEntity.Attributes["attachmentnumber"] = 1; attachmentEntity.Attributes["mimetype"] = "application/octete-stream"; byte[] binaryData = new Byte[x.InputStream.Length]; attachmentEntity.Attributes["body"] = System.Convert.ToBase64String(binaryData, 0, binaryData.Length); // Create the Attachment in CRM. attachmentId = _service.Create(attachmentEntity); } } } |