Adding Attachments to a Salesforce Record

Using a Contact Record as an Example


The type of file is typically a Word doc, PDF, xls, etc. You need to create an attachment and set its Parent ID to the ID of the Salesforce object that you are linking it to. Be aware the attachment body needs to be a byte array. Please Google converting different types of documents to a byte array using C#.


SalesforceSession salesforceSession = SessionTest.GetActiveSession();
ContactService contactService = new ContactService(salesforceSession);

AttachmentService attachmentService = new AttachmentService(salesforceSession);

//create a new contact
Contact contact = new Contact();
contact.FirstName = "John";
contact.LastName = "Doe";
SaveResult saveResult = contactService.SaveContact(contact);
string contactId = saveResult.id;


//create an attachment
Attachment attachment = new Attachment();
attachment.Name = "My attachment name";

//get the document as a byte array
byte[] bytes = System.IO.File.ReadAllBytes("MyPDF.pdf");
attachment.Body = bytes;

//set the Parent ID of the attachment to link it to the contact
attachment.ParentId = contactId;

//save the attachment
saveResult = attachmentService.Save(attachment);