Download Files from Salesforce Attachments

You can query the Attachment Body field, which will be exposed in .NET as a byte[].


SalesforceSession session = //...
AttachmentService attachmentService = new AttachmentService(session);

// Id might be via a relationship field or Attachment might come from a sub query.
Id attachmentId = new Id("00P9000000vVgYq");

Attachment attachment = attachmentService.GetByEntityId(attachmentId, new SObjectField[] { Attachment.Fields.Id, Attachment.Fields.Body, Attachment.Fields.BodyLength, Attachment.Fields.Name, Attachment.Fields.ContentType });

Assert.IsNotNull(attachment);
Assert.AreEqual("image/png", attachment.ContentType);

byte[] attachmentBody = attachment.Body;

Assert.AreEqual(attachment.BodyLength, attachmentBody.Length);

using (Image pngImage = Image.FromStream(new MemoryStream(attachmentBody)))
{
	pngImage.Save(attachment.Name,
	ImageFormat.Png);
}