0

How to dispose file stream in api ?

Let assume that I need to call this api 10 times.

[HttpGet("{fileName}")]
public async Task<IActionResult> Get(string fileName)
{
   var res = File.Open(path, FileMode.Open);
   var file = File(res, "application/zip", fileName);
   return file;
}

I can't dispose stream before is returned from api method.

When I call it second time I will get exception:

The process cannot access the file 'C:\test\example.zip' because it is being used by another process.

Raskolnikov
  • 3,103
  • 6
  • 31
  • 72

1 Answers1

1

First of all, remember about concurrency and thread safety. (many request can pass to your controller at the same time. And in this case if you are writing som,ething to the file - the behaviour of app can be wrong). If you are not writing to the file (only reading), then you can just specify the sharing mode for other threads like this:

using(var file = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){
   //your code goes here
}
n.prokhorov
  • 847
  • 7
  • 13
  • When using is ended, than stream will be disposed.How to return disposed stream? – Raskolnikov Sep 08 '16 at 13:24
  • You can copy your file stream to new stream inside this using. Look at Stream.CopyToAsync [link]https://msdn.microsoft.com/en-us/library/system.io.stream.copytoasync.aspx – n.prokhorov Sep 08 '16 at 13:29
  • Why would you want to return a disposed ressource? – HimBromBeere Sep 08 '16 at 13:30
  • I don't want to return disposed stream. I want to dispose stream after I return it. – Raskolnikov Sep 08 '16 at 13:32
  • If you need just to return file from this action - you can read this file as bytes, and then return it as File from controller, like this: http://stackoverflow.com/questions/3604562/download-file-of-any-type-in-asp-net-mvc-using-fileresult – n.prokhorov Sep 08 '16 at 13:35