While this particular question is about embeddedIO and FileReponseAsync but it probably has more to do with the handling of streams and async in Tasks in C#.
I am using EmbeddedIO (I needed a quick and dirty web server, and so far it has worked like a charm -- however the lack of documentation is a bit frustrating), but I am attempting to return a file with the following code:
var file = new FileInfo(Path.Combine(FileLocations.TemplatePath, templateFile.FilePath));
string fileExtension = Path.GetExtension(templateFile.FilePath);
return this.FileResponseAsync(file, MimeTypes.DefaultMimeTypes.Value.ContainsKey(fileExtension) ?
MimeTypes.DefaultMimeTypes.Value[fileExtension] : "application/octet-stream");
I get the following error:
Message
Failing module name: Web API Module
Cannot access a closed file.
Stack Trace
at System.IO.__Error.FileNotOpen()
Which makes sense, since in the EmbedIO code FileResponseAsync looks like:
using (FileStream fileStream = file.OpenRead())
return context.BinaryResponseAsync(fileStream, ct, useGzip);
and the filestream will be disposed as soon as the BinaryReponse returns. I've solved the problem by changing my code to not dispose of the filestream:
var fileStream = file.OpenRead();
return this.BinaryResponseAsync(fileStream);
While this works, it seems wrong to rely on Garbage Collection to dispose of these files at a later date. How are resources like this (not only in EmbeddedIO but in this modern async world) supposed to be handled?