-1

I'm trying to download some bytes over my xampp server to use it inside my C# program, but there is a difference between the length of the bytes as shown here :

        WebClient wc = new WebClient();
        byte[] bytesweb = wc.DownloadData(@"http://127.0.0.1/test.txt");

        int lenweb = bytesweb.Length; //The value of lenweb is 69
        

And then when I use the same bytes directly inside the program as shown here :

        byte[] bytesapp = new byte[] { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

        int lenapp = bytesapp.Length; //The value of lenapp is 11

So I can't understand what changed between thoses 2, what to do so the length value is equal to "11" while importing it using my server

nb : the value of "test.txt" is : { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

SharpIt777
  • 27
  • 5
  • @Heinzi, what do you mean ? – SharpIt777 Jun 20 '22 at 11:10
  • 4
    There are no byte formats. If one byte array has 67 bytes and the other 11, they aren't the same. Text files don't have `NUL` characters either, which means `test.txt` isn't a text file but something else – Panagiotis Kanavos Jun 20 '22 at 11:10
  • Why do you assume the hard-coded bytes in the second case are the same as the file anyway? Why not read the contents of the file instead, with `File.ReadAllBytes(pathToFile)` ? – Panagiotis Kanavos Jun 20 '22 at 11:12
  • @PanagiotisKanavos, It is actually a text file, I'm sure of that, they are exactly the same as shown on the post, didn't add anything. Because it's located on my server, that's why I'm trying to use it directly using WebClient, otherwise I would already done it using File.ReadAllBytes method – SharpIt777 Jun 20 '22 at 11:16

1 Answers1

5

nb : the value of "test.txt" is : { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

So, your file contains the literal text { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };.

This is a 69-byte text which, when interpreted as a C# code snippet, represents a 11-byte byte array. This explains the difference you see.


How do you fix this? Don't store your byte arrays as text, store them as a bytes:

byte[] bytesapp = new byte[] { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

// This creates the file you want to put on your web server.
File.WriteAllBytes(@"C:\temp\test.bin", bytesapp);

(Alternatively, you could write code that parses your text file and converts it to a "real" byte array. This question contains example code that can do this for you if you store your data in the following format: 0000400000e81000000040.)

Heinzi
  • 167,459
  • 57
  • 363
  • 519