C # como escrever tipo array tempo para arquivo binário
-
18-09-2019 - |
Pergunta
Eu tenho uma matriz long
. Como escrever essa matriz para um arquivo binário?
O problema é que se eu convertê-lo em conjunto byte
alguns valores são alterados.
A matriz é semelhante:
long array = new long[160000];
Dê algum trecho de código.
Solução
O BinaryFormatter será o mais fácil.
Além disso valuetypes (Eu suponho que este é o que você entende por muito tempo), serializa muito eficiente.
Outras dicas
var array = new[] { 1L, 2L, 3L };
using (var stream = new FileStream("test.bin", FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new BinaryWriter(stream))
{
foreach (long item in array)
{
writer.Write(item);
}
}
Como os valores alterados? E uma série de tempo pode ser copiado em um array de byte muito rapidamente, sem necessidade de serialização.
static void Main(string[] args) {
System.Random random = new Random();
long[] arrayOriginal = new long[160000];
long[] arrayRead = null;
for (int i =0 ; i < arrayOriginal.Length; i++) {
arrayOriginal[i] = random.Next(int.MaxValue) * random.Next(int.MaxValue);
}
byte[] bytesOriginal = new byte[arrayOriginal.Length * sizeof(long)];
System.Buffer.BlockCopy(arrayOriginal, 0, bytesOriginal, 0, bytesOriginal.Length);
using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) {
// write
stream.Write(bytesOriginal, 0, bytesOriginal.Length);
// reset
stream.Flush();
stream.Position = 0;
int expectedLength = 0;
checked {
expectedLength = (int)stream.Length;
}
// read
byte[] bytesRead = new byte[expectedLength];
if (expectedLength == stream.Read(bytesRead, 0, expectedLength)) {
arrayRead = new long[expectedLength / sizeof(long)];
Buffer.BlockCopy(bytesRead, 0, arrayRead, 0, expectedLength);
}
else {
// exception
}
// check
for (int i = 0; i < arrayOriginal.Length; i++) {
if (arrayOriginal[i] != arrayRead[i]) {
throw new System.Exception();
}
}
}
System.Console.WriteLine("Done");
System.Console.ReadKey();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow