Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

stream

I have a StreamReader object that I initialized with a stream, now I want to save this stream to disk (the stream may be a .gif or .jpg or .pdf).

Existing Code:

StreamReader sr = new StreamReader(myOtherObject.InputStream); 
  1. I need to save this to disk (I have the filename).
  2. In the future I may want to store this to SQL Server.

I have the encoding type also, which I will need if I store it to SQL Server, correct?

like image 561
Loadman Avatar asked Jan 04 '09 20:01

Loadman


People also ask

How do you save on MemoryStream?

Save MemoryStream to a String StreamWriter sw = new StreamWriter(memoryStream); sw. WriteLine("Your string to Memoery"); This string is currently saved in the StreamWriters buffer. Flushing the stream will force the string whose backing store is memory (MemoryStream).

What is file stream in C#?

The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare.

How do file streams work?

A stream is a sequence of bytes. In the NTFS file system, streams contain the data that is written to a file, and that gives more information about a file than attributes and properties. For example, you can create a stream that contains search keywords, or the identity of the user account that creates a file.


1 Answers

As highlighted by Tilendor in Jon Skeet's answer, streams have a CopyTo method since .NET 4.

var fileStream = File.Create("C:\\Path\\To\\File"); myOtherObject.InputStream.Seek(0, SeekOrigin.Begin); myOtherObject.InputStream.CopyTo(fileStream); fileStream.Close(); 

Or with the using syntax:

using (var fileStream = File.Create("C:\\Path\\To\\File")) {     myOtherObject.InputStream.Seek(0, SeekOrigin.Begin);     myOtherObject.InputStream.CopyTo(fileStream); } 
like image 153
Antoine Leclair Avatar answered Nov 04 '22 20:11

Antoine Leclair