Mahmood Bagheri
Mahmood Bagheri

Reputation: 163

save attachment file in microsoft dynamic crm to computer

CRM saves attachements in AnnotationBase base table.

How can I convert the text in the DocumentBody entity back to file and save it the file system?

I have got the value of the documentbody field and then try to write it in my computer but my is file corrupted.

I am using this code:

String DocumentBody = Convert.ToBase64String(
      newUnicodeEncoding().GetBytes("UEsDBBQABgAIAAAAIQDQf9XuxAEAAE4HAAATAAgCW0NvbnRlbnRfVHlwZXNd       Lnh/abtPgp4eu7+W68C2dvLaWtho32sTajdkFmweGeKMQYTD5MrcDFf"));

using (FileStream fs = new FileStream("c:\\1.docx", FileMode.Create, FileAccess.Write))
{
    byte[] bytes = Convert.FromBase64String(DocumentBody);
    fs.Write(bytes, 0, bytes.Length);
}

The string in GetBytes is the same as documentbody field in annotationBase table.

Upvotes: 0

Views: 4853

Answers (1)

Nicknow
Nicknow

Reputation: 7224

Here is the code that has always worked for me - and I can confirm this has worked for me using data retreived from CRM 4 with the CRM 4 SDK. I did a project almost exactly the same about 18 months ago where we had to archive off all the notes and e-mails from CRM.

If you are still having issues see the original source of this code

public static void ExportFile(string fileName, string content)
{
    byte[] fileContent = Convert.FromBase64String(content);
    using (FileStream file = new FileStream(fileName, FileMode.Create))
    {
        using (BinaryWriter writer = new BinaryWriter(file))
        {
            writer.Write(fileContent,0,fileContent.Length);
            writer.Close();
        }

        file.Close();
    }
}

Upvotes: 1

Related Questions