Programmatically downloading image files from Dynamics CRM 2011

Gayan Perera, 14 December 2011

We came across an issue with an upgrade from CRM 4 to CRM 2011 where the images were all messed up, transparency was gone and had pixelated images, there were over 100 custom entities and download/uploading these manually was not an option.

Here’s a small bit of code to download image web resources from Dynamics CRM 2011.

private static void DownloadIcons(IOrganizationService sdk, string path)
{
    QueryExpression qe = new QueryExpression("webresource");
    qe.ColumnSet = new ColumnSet("name", "webresourcetype", "content", "displayname");
 
    // 7 = gif, 10 = ico
    qe.Criteria.AddCondition("webresourcetype", ConditionOperator.In, new int[] { 7, 10 });
 
    Console.WriteLine("downloading, please wait...");
 
    var results = sdk.RetrieveMultiple(qe);
    var all = results.Entities.ToList();
 
    Console.WriteLine("found: {0} web resources", all.Count);
 
    if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }
 
    all.ForEach(a =>
    {
        var type = a.GetAttributeValue<OptionSetValue>("webresourcetype");
        string name = a.GetAttributeValue<string>("name") + ((type.Value == 7) ? ".gif" : ".ico");
 
        // remove any simulated paths using the schema name, eg: mag_/img/xyz.extension
        if (name.IndexOf("/") > -1)
        {
            name = name.Substring(name.LastIndexOf("/") + 1);
        }
 
        var content = Convert.FromBase64String(a.GetAttributeValue<string>("content"));
        File.WriteAllBytes(Path.Combine(path, name), content);
 
        Console.WriteLine("downloaded: {0}", name);
    });
 
    Console.WriteLine("all done!");
}