0

I am trying to convert a document in a SharePoint document library to byte array in restful WCF service. When I declared the byte array with the maximum size, i am getting the files size as the maximum that I had declared. I need to know how to declare the byte array dynamically.

Below is my code:

using (CSOM.ClientContext clientContext = new CSOM.ClientContext(SPserverUrl))
{
    DocumentID = "229"; 
    clientContext.Credentials = new System.Net.NetworkCredential(@"username", "pwd", "domain");
    CSOM.Web _Site = clientContext.Web;
    CSOM.List _List = _Site.Lists.GetByTitle("TestFiles");
    CSOM.ListItem listItem = _List.GetItemById(Convert.ToInt32(DocumentID));
    clientContext.Load(_List);
    clientContext.Load(listItem, i => i.File);
    clientContext.ExecuteQuery();           
    var fileRef = listItem.File.ServerRelativeUrl;
    var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
    byte[] buffer = new byte[9469417];
    // how to declare the above byte array dynamically with the file size dynamically
    using (MemoryStream memoryStream = new MemoryStream())
    {

        int bytesRead;
        do
        {
            bytesRead = fileInfo.Stream.Read(buffer, 0, buffer.Length);
            memoryStream.Write(buffer, 0, bytesRead);
        } while (bytesRead != 0);

        string base64 = Convert.ToBase64String(buffer);

    }
}
entryton
  • 280
  • 5
  • 18
TARUN
  • 241
  • 1
  • 8
  • 27

2 Answers2

3

I got the solution from the below link

http://ranaictiu-technicalblog.blogspot.co.uk/2010/06/sharepoint-2010-attach-files-to.html

               var fileRef = listItem.File.ServerRelativeUrl;
              var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
                var stream = fileInfo.Stream;
                IList<byte> content = new List<byte>();
                int b;
                while ((b = fileInfo.Stream.ReadByte()) != -1)
                {
                    content.Add((byte)b);
                }
                byte[] barray = content.ToArray();
TARUN
  • 241
  • 1
  • 8
  • 27
0

Your buffer doesn't need to be the same size as the file at all. You're only using it as temporary storage, to copy a chunk of the input file into your output MemoryStream.

I'd personally use something like 16K as the size - not big enough to end up in the large object heap, but not so small that you end up with lots of tiny IO operations.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Dear Jon. Thanks for the reply. As i already told i am trying to convert share point documents to byte array. so can I achieve this in any other way.. i need the document in byte arrary – TARUN Feb 01 '16 at 13:03