Home > Enterprise >  pass memory stream to another class how to close it
pass memory stream to another class how to close it

Time:07-05

I have a separate class to create CSV file and add it to memory stream and a separate class to send the file(upload it to the cloud storage) I did this separation because these are two different jobs, here is the class im creating memory stream:

public MemoryStream ExecuteUseCase(Myclass listOfStudents)
    {
        var memoryStream = new MemoryStream();
        var streamWriter = new StreamWriter(memoryStream);
        var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture);           
        csvWriter.WriteRecords(listOfStudents.FileBody);
        streamWriter.Flush();
        memoryStream.Position = 0;
        return memoryStream;              
        }
    }
    
    

as you can see I have removed the using from the block because if I add using there, they will close the stream and its not accessible in the other class, here is my second class:

     var memoryStream = this.convertToCsv.ExecuteUseCase(file);
            await blobClient.UploadAsync(memoryStream, true);
            
            this approach works, but my only concern is the memoryStream disposal, how to close it? Or do I need even? 

CodePudding user response:

Using in the class that uses it

using(var memoryStream = this.convertToCsv.ExecuteUseCase(file)){
    await blobClient.UploadAsync(memoryStream, true);
}
  •  Tags:  
  • c#
  • Related