1

I am able to upload the document but when I'm viewing/downloading it, there seems to be an error. It says it ran into a problem opening this PDF. Ran into a problem

I have the following code

using (var stream = new System.IO.MemoryStream())
{
    byte[] myByte = System.Text.ASCIIEncoding.Default.GetBytes(documentBody);
    foreach (byte element in myByte)
    {
        stream.WriteByte(element);
    }
    stream.Seek(0, SeekOrigin.Begin);
    var newFile = new FileCreationInformation { Url = fileName, ContentStream = stream, Overwrite = true };

    file = list.RootFolder.Files.Add(newFile);
    file.CheckOut();
    file.CheckIn(string.Empty, CheckinType.MajorCheckIn);
    context.Load(file);
    context.ExecuteQuery();
}

The documentBody is the field documentbody from Annotation (note). Is there something wrong with the stream?

rene
  • 41,474
  • 78
  • 114
  • 152
Judah Endymion
  • 67
  • 1
  • 12
  • So you try to create a a PDF by writing bytes from a documentBody, which is a simple string? If you want to create a PDF it needs to follow the format described [here](http://www.adobe.com/content/dam/Adobe/en/technology/pdfs/PDF_Day_A_Look_Inside.pdf). – rene Aug 03 '16 at 08:08
  • Thanks @rene but I copied a SharePoint document to CRM Notes using the `documentbody` as string and I can view it just fine. Does it still apply, besides, I'm not creating a PDF from scratch... – Judah Endymion Aug 03 '16 at 08:18
  • Besides inefficiency there is not much wrong with this code. What is the filename? And in that documentBody there is just plain text? But you do expect to return a PDF? – rene Aug 03 '16 at 08:22

1 Answers1

1

The documentBody is Base64 encoded in CRM, so you many need to decode it first before saving into SharePoint.

Try this to get the document data.

byte[] data = Convert.FromBase64String(e.Attributes["documentbody"].ToString());

James Wood
  • 17,286
  • 4
  • 46
  • 89
  • Thank you! It worked! However I believe the limit length for this is 2,147,483,647. Well common files don't exceed 2GB so I think this will suffice. – Judah Endymion Aug 03 '16 at 11:45