C # WebClient download a file which is twice as large as the original

I am testing some file uploads with WebApi 2.0. I created a controller that has a boot method and I also created a console app to do the boot. Am I doing something wrong with my save operation that causes the file to be twice the size?

Below screenshot shows the file that I am downloading and the file that is being saved from the server. Don't ask me why this file, I just selected something in the Downloads folder. enter image description here

Server code to save the 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 file upload:

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();
    }

      

+3


source to share


1 answer


You shouldn't use StreamReader

and StreamWriter

- those that are meant for text, and your content is not 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 changed the method to just return Task

as the part bool

seemed pointless ...)

0


source







All Articles