C# WebClient uploads file that is around twice as large as original

I am testing some file uploads using WebApi 2.0. I created a controller that has an upload method and I also created a console application to perform the upload. I am doing something wrong with my save operation that is causing the file to be around twice as large?

Below the screenshot shows the file I am uploading, and the file that gets saved from the server. Don't ask why that file, I just picked something in my Downloads folder. enter image description here

Server Code for saving file:

[RoutePrefix("api/Files")]
public class FileController : ApiController
{

    [Route("Upload")]
    public async Task<IHttpActionResult> UploadFileAsync()
    {


        await ReadStreamAsync(HttpContext.Current, @"C:\Users\Bailey Miller\Desktop\FTP\WebsiteUploads\" + Guid.NewGuid() + ".txt");

        return Ok();

    }

    private async Task<bool> ReadStreamAsync(HttpContext context, string filePath)
    {
        using (var reader = new StreamReader(context.Request.GetBufferlessInputStream(true)))
        using (var filestream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, true))
        using (var writer = new StreamWriter(filestream))
        {
            var readBuffer = await reader.ReadToEndAsync();
            await writer.WriteAsync(readBuffer);
        }

        return true;
    }

}

Client code for uploading file:

static void Main(string[] args)
    {
        WebClient _client = new WebClient();

        _client.UploadFile("https://localhost:44314/api/Files/Upload", @"C:\Users\Bailey Miller\Downloads\AccessDatabaseEngine.exe");

        Console.WriteLine("Waiting .. .. ..");
        Console.ReadLine();
    }
Jon Skeet
people
quotationmark

You shouldn't be using StreamReader and StreamWriter - those are for text, and your content isn't text. Just use Stream instead:

private async Task ReadStreamAsync(HttpContext context, string filePath)
{
    using (var input = context.Request.GetBufferlessInputStream(true))
    using (var output = File.Create(filePath))
    {
        await input.CopyToAsync(output);
    }
}

(I've changed the method to just return Task as the bool part seemed pointless...)

people

See more on this question at Stackoverflow