1
\$\begingroup\$

I am using following code to download a csv file using Web API. Maximum file size will be less than 500mb. How can I improve this code?

[HttpPost, Route("api/files/getfile")]
public HttpResponseMessage GetDataFileResponse(string filePath) {
    try {

        FileStream fileStream = File.OpenRead(filePath);
        long fileLength = new FileInfo(filePath).Length;

        var response = new HttpResponseMessage();
        response.Content = new StreamContent(fileStream);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = "mydata.csv";
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        response.Content.Headers.ContentLength = fileLength;
        return response;
    } catch (Exception e) {
        Console.WriteLine(e);
        throw;
    }
}
\$\endgroup\$
2
\$\begingroup\$

There can be two improvements in above code block initially as below:

  1. Method should be async, this will help your application in terms of performance for parallel requests
  2. In order to delete the large file, one should always prefer to download the file in chunks, again we are talking about parallel programming.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.