Updated on
To convert a stream to a file in C#, we create the file with File.Create() and copy the stream into it with CopyTo(), or CopyToAsync() in asynchronous code. A MemoryStream can also go through ToArray() and File.WriteAllBytes().
We’ll go through each way, look at its advantages and disadvantages, and benchmark them on .NET 11 to see when one is more suitable than another.
Let’s dive in.
What Is a Stream?
A stream is an abstraction of a sequence of bytes. The Stream class in .NET is an abstract class that implements the methods enabling stream operations, such as reading and writing to streams and positioning in a stream, among others.ย
The source and the destination of the sequence of the bytes can be various. For example, it can be a file, different input or output device, network, or similar. .NET implements a few classes that derive from the Stream class and deal with these different sources and destinations for a stream. That includes FileStream, MemoryStream, NetworkStream, and other classes.ย
When our data starts out as text, we can generate a stream from a string first and then save it the same way.
The Stream class and derived classes implement numerous methods for reading and writing from a stream, such as Read(), ReadAsync(), ReadByte(), Write(), WriteAsync(), and WriteByte().
How Do We Save a MemoryStream to a File?
To save a MemoryStream to a file, we create the file with File.Create(), set the stream’s Position back to 0, and call CopyTo() with the file stream as the destination. When the using declaration closes the file, every byte of the memory stream is on disk.
A MemoryStream can also hand over its whole content as an array through ToArray(). That gives us two more ways: File.WriteAllBytes() takes a path and the array, and FileStream.Write() takes the array as a span.
The two groups accept different sources. CopyTo() and CopyToAsync() are defined on Stream, so they also save a FileStream, a network stream or an HTTP response body to a file. ToArray() exists only on MemoryStream.
The file type makes no difference. If a library has rendered a PDF into a MemoryStream, the same call with a .pdf path saves the PDF.
Let’s describe several ways to convert a stream to a file in C#. First, we need to prepare our stream and path for a file:
var directory = AppContext.BaseDirectory; var sourceFile = Path.Combine(directory, "Files", "source.png"); var destinationPath = Path.Combine(directory, "Files"); using var fileStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read); using var memoryStream = new MemoryStream(); fileStream.CopyTo(memoryStream);
The source image is in the Files subfolder, and the project file copies it to the output folder next to our program with CopyToOutputDirectory set to PreserveNewest. We will store the resulting file in the same folder. We load the source image to a FileStream and copy this stream to a MemoryStream. This MemoryStream is the input parameter for all methods where we convert it to a file. The second parameter of this method is a path for the destination file.ย The stream itself is covered in MemoryStream in C#.
Convert a Stream to a File Using CopyTo
The CopyTo() method of theย Stream class copies from one stream to another:
public static class ConvertAStreamToAFileInCSharp
{
public static void CopyToFile(MemoryStream stream, string path)
{
using var fileStream = File.Create(path);
stream.Position = 0;
stream.CopyTo(fileStream);
}
}
We create a FileStream using the File.Create() method. The parameter of this method is the path where we want to save our file. After that, we position our source stream to 0 and then call the CopyTo() method on the Stream class. This class goes in its own file, and we’ll add every other method in this article to it.
If the file already exists, File.Create() overwrites it, so we never end up with leftover bytes from an older, longer file.
Convert a Stream to a File Using CopyToAsync
CopyToAsync() is the asynchronous twin of CopyTo(). We reach for it in a web application, or in any other asynchronous code:
public static async Task CopyToFileAsync(MemoryStream stream, string path)
{
await using var fileStream = File.Create(path);
stream.Position = 0;
await stream.CopyToAsync(fileStream);
}
The method returns a Task, and await using disposes the file stream asynchronously once the copy is done. If async and await are new to you, our article on asynchronous programming with async and await walks through them.
When the source is a FileStream or a network stream, CopyTo() and CopyToAsync() move the data in chunks through a buffer of up to 131,072 bytes by default. So a large stream never has to sit in memory all at once, which is not true of the ToArray() methods below.
Convert a Stream to a File Using Write
The FileStream.Write() method accepts aย ReadOnlySpan<byte> argument and writes it to a file:
public static void WriteToFileStream(MemoryStream stream, string path)
{
using var fileStream = File.Create(path);
fileStream.Write(stream.ToArray());
}
First, we convert the input stream to a byte[]. The ToArray() method of the MemoryStream class converts the stream content to an array entirely. In this case, we don’t have to position the input stream to 0 before writing to a file, as the ToArray() method writes the entire stream content to an array, regardless of the position.ย The Write() method then implicitly converts this array to a ReadOnlySpan<byte> and writes all bytes to a destination fileStream stream.
Convert a Stream to a File Using WriteByte
The FileStream class has the WriteByte() method, which accepts one byte and writes it to the file:
public static void WriteByteToFileStream(MemoryStream stream, string path)
{
using var fileStream = File.Create(path);
stream.Position = 0;
while (stream.Position < stream.Length)
{
fileStream.WriteByte((byte)stream.ReadByte());
}
}
After creating the destination fileStream stream and positioning the source stream at its first byte, we start a loop where we read one byte at a time with the ReadByte() method. This method returns an int value, so we must convert it to a byte data type that we write to the destination stream.ย
Convert a Stream to a File Using WriteAllBytes
The File class has a static WriteAllBytes() method that accepts the path and an array of bytes to write to the file:
public static void WriteAllBytesFile(MemoryStream stream, string path)
{
File.WriteAllBytes(path, stream.ToArray());
}
We pass the destination path to the static method and convert the input stream to the byte array.ย
If we already hold the bytes in an array, we can skip the stream completely, as our article on writing a byte array to a file shows.
Does Stream.CopyTo Start From the Current Position?
Yes. CopyTo() reads from the source stream’s current Position to its end, and it never rewinds the source for us. The Microsoft Learn page for Stream.CopyTo states that “Copying begins at the current position in the current stream,” and that the method does not reset the position of the destination stream when the copy is done.
That is why CopyToFile() sets stream.Position = 0 first. In our example, fileStream.CopyTo(memoryStream) has just filled the memory stream, and that copy left its position at the end.
If we skip the reset, CopyTo() finds nothing left to read. We get a file of zero bytes, and no exception tells us why.
After the copy, both positions have moved. The source sits at its end, and the destination has moved forward by the number of bytes written. Before we read either stream again, we set its position back to 0.
Let’s copy the stream into one file without rewinding it, and into a second one after rewinding:
Console.WriteLine($"Position after loading: {memoryStream.Position} of {memoryStream.Length}");
using (var noRewindFile = File.Create(Path.Combine(destinationPath, "NoRewind.png")))
{
memoryStream.CopyTo(noRewindFile);
Console.WriteLine($"Bytes written without rewinding: {noRewindFile.Length}");
}
memoryStream.Position = 0;
using (var rewindFile = File.Create(Path.Combine(destinationPath, "Rewind.png")))
{
memoryStream.CopyTo(rewindFile);
Console.WriteLine($"Bytes written after rewinding: {rewindFile.Length}");
Console.WriteLine($"Position after CopyTo: source {memoryStream.Position}, destination {rewindFile.Position}");
}
As we can see, the first file is empty:
Position after loading: 6961 of 6961 Bytes written without rewinding: 0 Bytes written after rewinding: 6961 Position after CopyTo: source 6961, destination 6961
Setting Position only works on a stream that can seek. A NetworkStream reports CanSeek as false and throws a NotSupportedException if we try, so with a network source we copy from wherever the stream is, which for a fresh response is its start.
Which Way of Writing a Stream to a File Is Fastest?
For a small file, none of them wins clearly. In our benchmark on .NET 11, CopyTo() and Write() both wrote the 6,961-byte sample image in 109 microseconds, and their error bars overlapped. WriteAllBytes() took 115 microseconds, six microseconds more.
The allocations differ a lot more. CopyTo() allocated a few hundred bytes per call, because a MemoryStream writes its internal buffer straight into the destination. Write() and WriteAllBytes() allocated more than 7 KB each, since ToArray() first copies the whole content into a new array. That array is as big as the stream, so the gap grows with the file.
WriteByte() and CopyToAsync() were clearly slower than CopyTo(), at 165 and 160 microseconds.
That makes CopyTo() our default, since it accepts any stream and allocated the least in our benchmark. In asynchronous code, CopyToAsync() takes its place.
In addition, we’ll benchmark each of these examples with BenchmarkDotNet to see the best way to perform this conversion from a performance perspective:
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Order;
[InProcess]
[MemoryDiagnoser]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
public class ConvertAStreamToAFileInCSharpBenchmark
{
private readonly MemoryStream _stream = new();
private string _destinationPath = string.Empty;
[GlobalSetup]
public void Setup()
{
_destinationPath = Path.Combine(AppContext.BaseDirectory, "Files");
using var fileStream = File.OpenRead(Path.Combine(_destinationPath, "source.png"));
fileStream.CopyTo(_stream);
}
[Benchmark]
public void CopyToBenchmark()
{
ConvertAStreamToAFileInCSharp.CopyToFile(_stream, Path.Combine(_destinationPath, "CopyTo.png"));
}
// one [Benchmark] method for each of the other four ways
}
The benchmark class lives in the same project, which references the BenchmarkDotNet package. The [GlobalSetup] method loads the image into the memory stream once, before any measurement, so every benchmark writes the same 6,961 bytes to its file.
To start it, Program.cs ends with BenchmarkRunner.Run<ConvertAStreamToAFileInCSharpBenchmark>(args: args);, with using BenchmarkDotNet.Running; at the top. Let’s run it with dotnet run -c Release:
| Method | Mean | Error | StdDev | Allocated | |----------------------- |---------:|--------:|---------:|----------:| | CopyToBenchmark | 109.0 us | 2.16 us | 4.74 us | 592 B | | WriteBenchmark | 109.0 us | 2.04 us | 4.93 us | 7576 B | | WriteAllBytesBenchmark | 115.0 us | 2.29 us | 6.60 us | 7424 B | | CopyToAsyncBenchmark | 160.3 us | 3.41 us | 10.01 us | 1260 B | | WriteByteBenchmark | 165.1 us | 3.67 us | 10.82 us | 4712 B |
As we can see, the timings of CopyTo(), Write() and WriteAllBytes() sit close together, and CopyToAsync() and WriteByte() take about 50 percent longer.
The Allocated column is easier to read. CopyTo() needs the least memory, and the two methods that call ToArray() pay for a full copy of the image on every call.
Conclusion
Summing up, we have several options for converting a stream to a file in C#. In speed, CopyTo(), Write() and WriteAllBytes() are very similar, so for small files the choice among them is mostly a matter of personal preference.
In memory, CopyTo() comes out ahead: it works with any stream and allocates the least, and CopyToAsync() does the same job in asynchronous code. Whatever method we choose, we rewind a stream we have just written before we copy it to a file.
Tested with .NET 11.0.0 and BenchmarkDotNet 0.15.8.






