How to save a stream to a file in C#?

Updated on     Kisan Patel

Problem:
How to save a stream to a file in C#?
Convert a byte array to pdf in c#
saving a file (from stream) to disk using c#

Solution:

For file Type you can rely on FileExtentions and for writing it to disk you can use BinaryWriter. or a FileStream.

Example (Assuming you already have a stream):

namespace:

using System.IO;
var path = "~/Content/pdf/filename.pdf");

using (FileStream fileStream = System.IO.File.Create(path, (int)stream.Length))
{
       // Fill the bytes[] array with the stream data
       byte[] bytesInStream = new byte[stream.Length];
       stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

       // Use FileStream object to write to the specified file
       fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}

C#