Downloading Files in the .Net application from Salesforce with Rest API

|
| By Harleen Kaur

In Salesforce Classic, files are stored in the form of attachments, and in Lightning, we have Salesforce Files which are stored with more linked information through different objects, such as ContentDocument, ContentVersion, ContentDocumentLink.The ContentDocument being the parent object acts as an individual file, along with its versions stored in the ContentVersion and information of linked shared entities in ContentDocumentLink.The ContentDocumentId field in ContentVersion and ContentDocumentLink is the reference field that points to the Id field of the Parent Object ContentDocument.

Files are stored as blob objects in Salesforce. So Salesforce provides us with the REST API endpoint in the format as shown below:-

"{SALESFORCE_INSTANCE_URL}/{SALESFORCE_SERVICE_VERSION_URL}/sobjects/{SALESFORCE_OBJECT_TYPE}/{SALESFORCE_FILE_ID}/{SALESFORCE_BLOB_COLUMN}"

For example, if you want to download a file from the Attachments object, the request url can be in the format:

https://OrgDomainName.my.salesforce.com/services/data/v61.0/sobjects/Attachment//body

Here represents the Id column of the Attachment Object.

In the case of the Salesforce File inside Lightning, the file is represented as ContentDocument, but the blob field is inside ContentVersion where column IsLatest indicates the latest version of the blob

https://OrgDomainName.my.salesforce.com/services/data/v61.0/sobjects/ContentVersion//VersionData

Here represents the Id column of the ContentVersion object.

The Salesforce REST API endpoint applies to standard objects such as Attachment, ContentNote, ContentVersion, Document, Folder, and Note which contain blob fields.

Blob is accessed as a byte array in the .Net. The sample method for downloading the salesforce blob is as follows:

public async Task<byte[]> GetSalesforceBlobAsync(string requestUri, string blobColumn)
{
try
{
using (HttpClient client = new HttpClient())
{

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
);
HttpResponseMessage response = await client.GetAsync(requestUri);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsByteArrayAsync();
}
else
{
Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");

}
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
return null;
}

Leave a Reply

Your email address will not be published. Required fields are marked *