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);
}
}
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.
See more on this question at Stackoverflow