D
D
Danil Vaskevich2021-10-10 09:45:19
C++ / C#
Danil Vaskevich, 2021-10-10 09:45:19

How to extract two variables from a binary file?

I have a binary file in which I have written two variables (string and int). I need to get them out of there and write them to the class. I wrote part of the code but it doesn't work correctly.
Here is my code:

static Product ReadProduct(string fname)
        {
            Product product = new Product(" ", 0);

            using (FileStream f = new FileStream(fname, FileMode.Open))
            {
                byte[] strBytes = new byte[sizeof(char)];
                f.Read(strBytes, 0, strBytes.Length);
                for (int i = 0; i < f.Length; i++)
                {
                    f.Read(strBytes, 0, strBytes.Length);
                    string str = Encoding.Default.GetString(strBytes);

                    if (str != " ")
                    {
                        product.Name += str;
                    }
                    else
                        break;
                }
                byte[] priceBytes = new byte[sizeof(int)];
                f.Read(strBytes, 0, strBytes.Length);
                product.Price = BitConverter.ToInt32(priceBytes, 0);

            }
            return product;
        }


My code is reading a file and writing it, but I see wrong characters in the output. I will be glad for any help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Station 72, 2021-10-10
@cjstress

Well, this code certainly looks strange.
He's probably still in error.
Why not read the file in one line?
string text = await File.ReadAllTextAsync(filePath);
And the product information needs to be stored in an object format, such as JSON

V
Vasily Bannikov, 2021-10-10
@vabka

In general, IMHO, you have a rather strange idea to come up with some kind of your own format for data.
Why not json, not protobuf, not msgpack, or at least the same BinarySerializer?
one.

My code reads a file and writes it, but I see wrong characters in the output

So either reads or writes incorrectly.
2.
f.Read(strBytes, 0, strBytes.Length); //Зачем тут эта строка, если дальше в цикле идёт чтение?
                //Длина стрима считается в байтах, а char имеет размер 2, а не 1
                for (int i = 0; i < f.Length; i++)
                {
                    // А кто будет проверять, сколько по факту прочитано байтов и дочитывать непрочитанное?
                    f.Read(strBytes, 0, strBytes.Length);
                   // А кем гарантирована кодировка?
                  //Иногда Encoding.Default может кинуть NotSupportedException, так что лучше использовать конкретную кодировку
                    string str = Encoding.Default.GetString(strBytes);

                    if (str != " ") // А кто гарантирует, что в середине вашей строки не будет пробелов?
                    {
                        product.Name += str; //Лучше использовать StringBuilder
                    }
                    else
                        break;
                }

3. The price reading is strange (see variable names)
byte[] priceBytes = new byte[sizeof(int)];
                f.Read(strBytes, 0, strBytes.Length);
                product.Price = BitConverter.ToInt32(priceBytes, 0);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question