meme
meme

Reputation: 637

Error: The stream is invalid or no corresponding signature was found

I have this code:

MemoryStream recChunk = new MemoryStream();
byte[] sizeChunkB = new byte[10];
int sizeChunk;
streamLigacao.Read(sizeChunkB, 0, sizeChunkB.Length);
sizeChunk = BitConverter.ToInt32(sizeChunkB, 0);

int timesToEnter = (int)Math.Ceiling(sizeChunk / 1024.0);

for (int i = 0; i < vezesaEntrar; i++) {
    int size = streamLigacao.Read(RecData, 0, RecData.Length);
    recChunk.Write(RecData, 0, size);
}
recChunk.Position = 0;
MemoryStream deCompressed = new MemoryStream();

using (var tmp = new SevenZipExtractor(recChunk)) {   
    tmp.ExtractFile(0, deCompressed);
}
recChunk.Close();

And it is returning this error:

The stream is invalid or no corresponding signature was found.

STREAMLIGACAO is a networkstream

What am i doing wrong?

Upvotes: 0

Views: 677

Answers (1)

Luaan
Luaan

Reputation: 63772

There's a lot of issues with your code. Most importantly:

  • Read returns the amount of bytes read. If you ignore that, you're writing more than you've read, causing trouble.
  • Streams don't "reset" automatically - recChunk is at the end, so anyone reading from it will just exit immediately. You have to do recChunk.Position = 0; first.
  • (int)Math.Ceiling(sizeChunk / 1024.0) may not be accurate enough. You really want to stay with integer mathematics, rather than involving floating points.
  • Additionally, it shows that you expect a value that isn't an integer multiple of 1024, and yet you're assuming that you'll read (and write) exactly RecData.Length * timesToEnter bytes of data. That's fishy.

It's not clear what data is supposed to be in recChunk - I'm assuming it's a valid compressed bytestream understood by the decompression library of your choice.

EDIT:

Since your input stream is a TCP stream, all the above is even more important. A better read-write loop would look something like this:

var remainingBytes = sizeChunk;
var buffer = new byte[4096];

while (remainingBytes > 0)
{
  var bytesRead = streamLigacao.Read(buffer, 0, buffer.Length);
  if (bytesRead == 0) throw new InvalidOperationException("Connection closed.");

  recChunk.Write(buffer, 0, bytesRead);
}

Upvotes: 0

Related Questions