Dynamics CRM Code Snippet: Get Maximum Attachment Size Limit

If you are ever working with any code that needs to upload attachments to Dynamics CRM, you may run into an issue where your attachment is larger than the default of 5MB.

To prevent errors from occurring, you can check the Organizational Setting for the maximum upload file size, using code like this:

public int GetAttachmentSizeLimit()
{
    var size = -1;

    var query = new QueryExpression("organization")
    {
        ColumnSet = new ColumnSet("maxuploadfilesize")
    };

    var results = _proxy.RetrieveMultiple(query);

    if (results.Entities.Count == 0)
    {
        return size;
    }

    return results[0].GetAttributeValue<int>("maxuploadfilesize");
}

Depending on how you are uploading the attachment, you can either present the user with a warning (if uploading a single attachment), or ignore the attachment and add it to an exception report if running in a batch operation.

This setting can be found under Settings, Administration, System Settings, on the Email tab:

system settings - file upload size