Search code examples
tridiontridion-2011core-services

Tridion core service How to download binary file of a multimedia component


I have a requirement where I need to download binary file of a multimedia component but when I access the properties exposed of BinaryContentData class then there is no property to download an image file. Although for uploading file, Core Service have a property namely UploadFromFile.

So is there a way to download binary file to a temp location. Below is the code I am using:

core_service.ServiceReference1.SessionAwareCoreService2010Client client = new SessionAwareCoreService2010Client(); 
client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName"; 
client.ClientCredentials.Windows.ClientCredential.Password = "myPassword"; client.Open();
ComponentData component = (ComponentData)client.TryCheckOut(
                            multimediaComponentURI, new ReadOptions());
BinaryContentData binaryData =   component.BinaryContent;

Please Suggest.


Solution

  • There is a helper function called streamDownloadClient.DownloadBinaryContent inside Tridion.ContentManager.CoreService.Client.dll that you can use.

    I have created the following function that I usually reuse for that purpose:

    private static void CreateBinaryFromMultimediaComponent(string tcm)
    {
        Tridion.ContentManager.CoreService.Client.StreamDownloadClient streamDownloadClient = new StreamDownloadClient();
        SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2011");
    
        ComponentData multimediaComponent = client.Read(tcm, new ReadOptions()) as ComponentData;
    
        // Generate you own file name, and file location
        string file = "D:\\MyTempLocation\\" + Path.GetFilename(multimediaComponent.BinaryContent.Filename);;     
    
        // Write out the existing file from Tridion
        FileStream fs = File.Create(file);
        byte[] binaryContent = null;
    
        if (multimediaComponent.BinaryContent.FileSize != -1)
        {
            Stream tempStream = streamDownloadClient.DownloadBinaryContent(tcm);
            var memoryStream = new MemoryStream();
            tempStream.CopyTo(memoryStream);
            binaryContent = memoryStream.ToArray();
        }
    
        fs.Write(binaryContent, 0, binaryContent.Length);
        fs.Close();
    }