Search code examples
c#streamreadermemorystreamstringstreamdotnetzip

Converting DotNetZip memory stream to string


I am trying to read a file within a zip to check if that file has a certain string in it. But I can seem to get the "file" (memory stream) into a string in order to search it.

When I use the following code "stringOfStream" is always blank, what am I doing wrong? The reader always has a length and read byte returns different numbers.

        using (ZipFile zip = ZipFile.Read(currentFile.FullName))
        {
            ZipEntry e = zip[this.searchFile.Text];

            using (MemoryStream reader = new MemoryStream())
            {
                e.Extract(reader);
                var stringReader = new StreamReader(reader);
                var stringOfStream = stringReader.ReadToEnd();
            }

        }

Thanks


Solution

  • I think when you call Extract the position of the stream goes to the end of the file, so you need to reposition again to get the data.

    Can you try this please :

     using (ZipFile zip = ZipFile.Read(currentFile.FullName))
     {
                ZipEntry e = zip[this.searchFile.Text];
    
                using (MemoryStream reader = new MemoryStream())
                {
                    e.Extract(reader);
                    reader.Position = 0;
                    var stringReader = new StreamReader(reader);
                    var stringOfStream = stringReader.ReadToEnd();
                }
    
      }
    

    Check if it works or not.