How to migrate your code for uploading files from .NET Framework to .NET Core

I recently had to migrate code, for uploading Excel, files from an older .NET Framework application to a new one which is based on .NET Core. I would like to share my learnings with you in a “before and after” form.

No HttpRequestBase any more

You will have to replace the HttpResponseBase class from the System.Web assembly with the HttpResponse class from Microsoft.AspNetCore.Http.HttpResponse. The HttpResponse is the object that you receive from the UI in your WebAPI controller.

More information about this can be found here.

Uploaded file is not in InputStream to be found, but in Body

In the older .NET Framework you would access the stream through the HttpResponseBase.InputStream property. In the new .NET Core world you access it with the HttpResponse.Body property.

More information about it here.

No Length property anymore. Use the ContentLength property instead

After you read the stream you want to convert it into a byte array. For that you will first have to instantiate the byte array and you will need to know its length based on the length of the stream.

You will do that by accessing the HttpResponse.ContentLength property.

Here is the relevant question from StackOverflow.

Use the async method Stream.ReadAsync instead of Stream.Read

Replace Stream.Read() with the preferred Stream.ReadAsync() method to write the stream data into the byte array.

However, this also might do not read all the Bytes with one parse. For that you will have to use a while loop and count the last bytes read till you reach the end of the byte array.

More information can be found here.

How the final code looks like

1
2
3
4
5
6
7
8
9
10
11
Stream stream = request.Body;
int contentLength = (int)request.ContentLength.Value;
int numberOfBytesRead = 0;

byte[] data = new byte[contentLength];

while(numberOfBytesRead < contentLength)
{
    int readBytes = await stream.ReadAsync(data, numberOfBytesRead, contentLength - numberOfBytesRead);
    numberOfBytesRead += readBytes;
}
comments powered by Disqus