1 o più byte troncamento con gzip di andata e ritorno
-
21-08-2019 - |
Domanda
I dont farlo. Ho usato uno stesso approccio simile / ormai da molti anni, e mai sperimentato questo.
Per qualche ragione, che io non prendo in mano fino ad oggi, a GZip andata e ritorno si traduce in 1 o più byte di essere troncato o dati in fase di confuso.
ho scritto un semplice test per verificare che qualcosa d'altro non è che lo riguardano.
Questo non sempre con un 'lunghezza di mancata corrispondenza'.
Qualcuno può conforme a me che non mi fa impazzire? :)
Grazie
leppie
test
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
class Program
{
const int BUFFER_SIZE = 8192;
static void Main(string[] args)
{
var filename = args[0];
var filedata = File.ReadAllBytes(filename);
var cmp = Compress(filedata);
var dec = Decompress(cmp);
Assert(filedata, dec);
Console.ReadLine();
}
static void Assert(byte[] orig, byte[] data)
{
if (orig.Length != data.Length)
{
Debug.Fail("length mismatch");
}
for (int i = 0; i < orig.Length; i++)
{
Debug.Assert(orig[i] == data[i], "data mismatch");
}
}
static byte[] Compress(byte[] data)
{
var input = new MemoryStream(data);
var output = new MemoryStream();
var s = new GZipStream(output, CompressionMode.Compress);
byte[] buffer = new byte[BUFFER_SIZE];
int read = 0;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
s.Write(buffer, 0, read);
}
return output.ToArray();
}
static byte[] Decompress(byte[] data)
{
var input = new MemoryStream(data);
var s = new GZipStream(input, CompressionMode.Decompress);
var output = new MemoryStream();
byte[] buffer = new byte[BUFFER_SIZE];
int read = 0;
while ((read = s.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
return output.ToArray();
}
}
Ho provato con chiusura dei flussi correttamente anche con differenti dimensioni del buffer, lo stesso risultato.
Soluzione
OK, trovato il problema.
È necessario chiudere il flusso di compressione prima di recuperare i byte.
Esempio:
s.Close();
return output.ToArray();