0

I would like to know why after downloading a file from a Web-Server (the last line of the *.hex file does not contain anything, it is just an empty line) it saves the last line of the new file with NULL which increases the size of my *.hex file:

        byte[] buffer = null;

        using (FileStream fs = new FileStream("Drive of the server: //download.hex", FileMode.Open, FileAccess.Read))
        {
            buffer = new byte[fs.Length];       
            fs.Read(buffer, 0, (int)fs.Length);
        }

        var cd = new System.Net.Mime.ContentDisposition
        {
            FileName = "Fresh_copy_of_the_file" + ".hex",
            Inline = false,
        };

        Response.AppendHeader("Content-Disposition", cd.ToString());

        return File(buffer, "application/octet-stream");

enter image description here

Tsahi Asher
  • 1,767
  • 15
  • 28
V B
  • 27
  • 4
  • is this ASP.NET MVC? Core? – Tsahi Asher Apr 22 '19 at 13:39
  • Yes, ASP.NET MVC. Thanks – V B Apr 22 '19 at 13:51
  • 4
    Because you are reading into your buffer, but the fs.Read() method does not necessarily read the entire file. So your buffer could be left with nulls after that. You need to put the fs.Read() method into a while loop do { int bytesRead = fs.Read(...); } while (bytesRead > 0); That way it will keep reading from the file in chunks until the whole thing is read. You will need to append each read to your buffer[] array – Jon Apr 22 '19 at 13:51
  • @Jon : Yes, your intention is absolutely right, but the thing is it reads indeed the whole file, like it should be. But at the end of the new file he writes NULL, and it should be just an empty line ( like the original one): – V B Apr 22 '19 at 14:04
  • Try the solutions here https://stackoverflow.com/questions/9541351/returning-binary-file-from-controller-in-asp-net-web-api – Jon Apr 22 '19 at 14:12

0 Answers0