How to save a Stream to a file in C#? Correct approaches and examples
Hi everyone! I'm a beginner C# developer and I've encountered a task: I have a `Stream` object (for example, I got it from an HTTP request or from memory), and I need to save all its contents to a file on disk.
At first, I tried the simplest approach: read the stream into a byte array using `Read()` and then write it via `File.WriteAllBytes`. Here's my code:
public void SaveStreamToFile(Stream inputStream, string filePath)
{
byte[] buffer = new byte[inputStream.Length];
inputStream.Read(buffer, 0, buffer.Length);
File.WriteAllBytes(filePath, buffer);
}
But this code crashes with an error if the stream doesn't support seeking (for example, a network stream). Also, I've read that there can be memory issues with large files.