У меня есть бинарный файл в который я записал две переменные(string и int). Мне нужно вытащить их оттуда и записать в класс. Я написал часть кода но он не работает правильно. Вот мой код:
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;
}
Мой код считывает файл и записывает его, но на выводе я вижу неправильные символы.
Код записи в файл:
static void WriteProduct(Product product,string fname)
{
using (FileStream f = new FileStream(fname, FileMode.Create))
{
byte[] strBytes = Encoding.Unicode.GetBytes(product.Name);
f.Write(strBytes, 0, strBytes.Length);
byte[] slashn = Encoding.Unicode.GetBytes("\n");
f.Write(slashn, 0, slashn.Length);
byte[] priceBytes = BitConverter.GetBytes(product.Price);
f.Write(priceBytes, 0, priceBytes.Length);
}
}
Вот вывод: M i l k жяяяяяяяяяяяяяяяяя 0