Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it necessary to Dispose objects contains IFormFile (binary file) asp.net core 2

I am working on an upload service API on asp.net core 2 and since I am working with files I am wondering if is it necessary to implement IDispose interface and call Dispose() method after I am done from the object that contains the file or leave it to .net core framework to call garbage collector.

Edit 1: (here's part of my code)

 public class UploadFileModel
{
    [Required]
    public IFormFile FileBinary { get; set; }

    [Required]
    [MaxLength(50)]
    public string Type { get; set; }
}
like image 665
Mohammad Musaab Al-Türk Avatar asked Nov 29 '25 19:11

Mohammad Musaab Al-Türk


1 Answers

I would say no, there is no need to do that. Usually Microsoft implements IDisposable on types that need to be disposed like the DbContext from ef-core. The implementation of IFormFile contains a stream, that is being disposed in a finally statement when calling

Task CopyToAsync(Stream target, CancellationToken cancellationToken = default (CancellationToken));

You only need to make sure that you close the stream you pass in.

For example:

public async Task<IActionResult> Index(UploadFileModel requestModel)
{
    using (var myMemoryStream = new MemoryStream()) 
    {
        requestModel.FileBinary.CopyToAsync(myMemoryStream);

        // Use new memory stream (myMemoryStream) here...

    } // myMemoryStream is disposed of here
}
like image 87
alsami Avatar answered Dec 02 '25 18:12

alsami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!