How to Convert a Stream to MemoryStream

11,741

Solution 1

CopyTo is a void method so returns nothing, try the following:

var a = new MemoryStream();
content.CopyTo(a);
engine.SetDocument(a);

Solution 2

using (MemoryStream ms = new MemoryStream())
using (FileStream file = new FileStream("file.bin", FileMode.Open, FileAccess.Read)) 
{
   byte[] bytes = new byte[file.Length];
   file.Read(bytes, 0, (int)file.Length);
   ms.Write(bytes, 0, (int)file.Length);
}
Share:
11,741

Related videos on Youtube

Andres Carvajal
Author by

Andres Carvajal

Updated on May 26, 2022

Comments

  • Andres Carvajal
    Andres Carvajal almost 2 years

    In My code try:

    data expected

    Stream Content

    engine.SetDocument((MemoryStream)content); //No work
    

    Or

    var a = new MemoryStream();
    engine.SetDocument(content.CopyTo(a)); //Error 
    
    • LarsTech
      LarsTech about 8 years
      Looks like it wants a MemoryStream. Try SetDocument(a);
    • D Stanley
      D Stanley about 8 years
      @AndresCarvajal Stream is abstract - so it must be something more specific in reality. It may or may not be a MemoryStream, so casting is not safe. What are you needing to do that requires a Memorystream?
  • Diomos
    Diomos over 5 years
    this one is smooth