Question

I have developed ASP.NET web API. I am trying to read content of an excel file and trying to return it as bytes. I am getting following error:

The process cannot access the file 'C:\app\MyHost.AppServices\bin\Debug\temp\888.xlsx' because it is being used by another process.

I am using below code.I am not sure what is causing this error. Please provide your suggestions

public class FileController : MyBase
    {
        public HttpResponseMessage Get(string id)
        {


            if (String.IsNullOrEmpty(id))
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            var path = Path.Combine("temp", id);
            var fileStream = File.Open(path, FileMode.Open);
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            //response.Content = new StreamContent(fileStream);


            response.Content = new StreamContent(new FileStream(path, FileMode.Open, FileAccess.ReadWrite));
            response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = id;

            return response;

            }
    }
Was it helpful?

Solution

You never dispose the file from var fileStream = File.Open(path, FileMode.Open);, leaving it locked.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top