3

I would like to read a binary file from a zip file without unzipping it .

The zip file structure:

zipFolderName/subFolder/BinFile

In the BinFile, I have:

Id1, id2, value1 // id1, id2 are string, value1 is int

In C#:

 ZipEntry binFileName = …; // it has been got from zipFile entries
 MemoryStream ms  = new MemoryStream();
 binFileName.Extract(ms);

using (BinaryReader reader = new BinaryReader(ms))
{
    string id1 = reader.ReadString(); // error popped here
    string id2 = reader.ReadString();
    int value1 = reader.ReadInt32();
}

I got error: Unable to read beyond the end of the stream. It seems that BinaryReader cannnot read MemoryStream ?

user3448011
  • 1,469
  • 1
  • 17
  • 39
  • Did you try seeking to the start of the memory stream before trying to read from it? – Rowland Shaw May 09 '17 at 16:10
  • Note that BinaryReader.ReadString does expect that the string length prefixes the string in the stream in a certain data format. If this string length data is not there, the method will misinterpret the byte data in the stream and behave funny... –  May 09 '17 at 16:17
  • A memory stream has only one position (unlike unix which has both a read and write poistion). So when you write to a memory stream the position is left at the end of the stream. So before you read you must set the poisition back to zero. – jdweng May 09 '17 at 16:26

1 Answers1

4

After binFileName.Extract(ms); try the following:

ms.Seek(0, SeekOrigin.Begin);
Patrick McDonald
  • 64,141
  • 14
  • 108
  • 120