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

后端 未结 10 2271
我寻月下人不归
我寻月下人不归 2020-11-22 03:06

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

10条回答
  •  别跟我提以往
    2020-11-22 04:05

    Another option is to get the stream to a byte[] and use File.WriteAllBytes. This should do:

    using (var stream = new MemoryStream())
    {
        input.CopyTo(stream);
        File.WriteAllBytes(file, stream.ToArray());
    }
    

    Wrapping it in an extension method gives it better naming:

    public void WriteTo(this Stream input, string file)
    {
        //your fav write method:
    
        using (var stream = File.Create(file))
        {
            input.CopyTo(stream);
        }
    
        //or
    
        using (var stream = new MemoryStream())
        {
            input.CopyTo(stream);
            File.WriteAllBytes(file, stream.ToArray());
        }
    
        //whatever that fits.
    }
    

提交回复
热议问题