Stream to Base64String - Out of memory exception

Nirenjana Raghupathy 26 Reputation points
2022-08-11T08:17:53.67+00:00

Hi,

We are trying to read a file from Sharepoint document library and convert it to Base64 string using the below code:
var spFile = ctx.Web.GetFileByServerRelativeUrl(fileUrlPath);
var spFileContent = spFile.OpenBinaryStream();
ctx.Load(spFile);
ctx.ExecuteQuery();
MemoryStream stream = new MemoryStream();
if (spFileContent != null && spFileContent.Value != null)
{
spFileContent.Value.CopyTo(stream);
}
return Convert.ToBase64String(stream.ToArray());

We are getting a "System.OutOfMemory exception" while converting the stream array to Base64 string.
Does anyone know a solution for this?

Microsoft 365 and Office | SharePoint | For business | Windows
Developer technologies | .NET | .NET CLI
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. satya karki 996 Reputation points MVP
    2022-08-11T09:02:06.247+00:00

    Hi,

    try this way

    var file = clientContext.Web.GetFileByServerRelativeUrl(oAttachment.ServerRelativeUrl);    
                clientContext.Load(file);    
                clientContext.ExecuteQuery();    
                ClientResult<System.IO.Stream> data = file.OpenBinaryStream();    
                clientContext.Load(file);    
                clientContext.ExecuteQuery();    
                using (System.IO.MemoryStream mStream = new System.IO.MemoryStream())    
                {    
                   if (data != null)    
                   {    
                      data.Value.CopyTo(mStream);    
                      byte[] imageArray = mStream.ToArray();    
                      imgBase64Str = Convert.ToBase64String(imageArray);    
                   }    
                }    
    

    https://www.c-sharpcorner.com/article/read-list-item-attachmentimage-and-convert-into-base64-string-csom-using-app-o/

    1 person found this answer helpful.

  2. Rijwan Ansari 766 Reputation points MVP
    2022-08-11T09:10:57.553+00:00

    Hi,

    You can use below code for your case.

    string imgBase64Str = "";  
    var spFile = ctx.Web.GetFileByServerRelativeUrl(fileUrlPath);  
    var spFileContent = spFile.OpenBinaryStream();  
    ctx.Load(spFile);  
    ctx.ExecuteQuery();  
    using (MemoryStream stream = new MemoryStream())    
         {  
    	if (spFileContent != null && spFileContent.Value != null)  
             {  
    		spFileContent.Value.CopyTo(stream);  
    		byte[] imageArray = mStream.ToArray();  
    		imgBase64Str = Convert.ToBase64String(imageArray);  
             }  
         }    
      
    return imgBase64Str  
    
    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.