How to return a Stream from a method, knowing it should be disposed?

后端 未结 3 1052
囚心锁ツ
囚心锁ツ 2021-01-01 10:55

I have a method that takes FileStream as input. This method is running inside a for loop.

private void UploadFile(FileStream fileStream)
{
    var stream = G         


        
3条回答
  •  醉酒成梦
    2021-01-01 11:12

    When you return an IDisposable from a method, you are relegating the responsibility of disposing it to your caller. Thus, you need to declare your using block around the entire usage of the stream, which in your case presumably spans the UploadFile call.

    using (var s = GetFileStream())
        UploadFile(s);
    

提交回复
热议问题