Q:

WebApi File Read Access is Denied

I have a WebApi application whose intent is to serve up audio files, located within the application.  They are stored in the app_data/audio folder.
Here is my method of retrieval:
public HttpResponseMessage Get(string file)
    {
        var path = String.Format("{0}{1}", HttpContext.Current.Server.MapPath(@"~/App_Data/Audio/"), file);

        try
        {
            var responseStream = new MemoryStream();
            using (Stream fileStream = File.Open(path, FileMode.Open))
            {
                fileStream.CopyTo(responseStream);
                fileStream.Close();
                responseStream.Position = 0;
            }
            var response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StreamContent(responseStream)
                };

            response.Content.Headers.Add("content-type", "audio/basic"); 
            response.Headers.CacheControl = new CacheControlHeaderValue()
            {
                Private = true
            };

            response.Content.Headers.Expires = null;
            response.Headers.Pragma.Clear();

            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = file
            };

            return response;
        }
        catch (Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, e.Message);
        }
    }

Unfortunately, I get this error:

"Access to the path 'F:\Apps\AudioServeup\App_Data\Audio\test.pcm' is denied."

I can resolve this by setting the AppPool identity to NetworkService, then giving NetworkService Write Access.  Huh?  Not sure why I would require that, because NetworkService has read access by default.
Any ideas?
Thanks!

A:

Try File.OpenRead( instead of File.Open( as that will ensure it only requests read access when opening the file.

