Stream to Base64String - Out of memory exception

Nirenjana Raghupathy 21 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?

SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,601 questions
.NET CLI
.NET CLI
A cross-platform toolchain for developing, building, running, and publishing .NET applications.
322 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. satya karki 986 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 746 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.