0

Here is my code:

using (ZipArchive zip = ZipFile.Open(path, ZipArchiveMode.Read))
    foreach (ZipArchiveEntry entry in zip.Entries)
        if (entry.Name == "example.txt")
            entry.ExtractToFile(???);

The ??? is what I'm having trouble with. I want it to go to a string, not a file on disk.

TheTank20
  • 89
  • 1
  • 6
  • ZipArchiveEntry class has `Open` method which returns a Stream. You can read that stream using streamReader to a string. Check the most voted answer of [this question](https://stackoverflow.com/questions/17801761/converting-stream-to-string-and-back-what-are-we-missing) to see how stream can be read to a string. – Chetan Feb 12 '22 at 00:09
  • "Without extracting the zip" - you can't, unless the zip was created with no compression and you can read the string directly as bytes from the file – Caius Jard Feb 12 '22 at 00:33

1 Answers1

2

The first code will get you an Array of String, as if it were "ReadAllLines". The second one will get you a single String (as if it were "ReadAllText").

List<string> lines = new List<string>();
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
    foreach (ZipArchiveEntry entry in archive.Entries.Where(e_ => e_.Name == "example.txt"))
    {
        Stream stream = entry.Open();
        using (var sr = new StreamReader(stream, Encoding.UTF8))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                lines.Add(line);
            }
        }
    }
}
string[] result = lines.ToArray();




string result = "";
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{    
    foreach (ZipArchiveEntry entry in archive.Entries.Where(e_ => e_.Name == "example.txt"))
    {
        Stream stream = entry.Open();    
        using (var sr = new StreamReader(stream, Encoding.UTF8))
        {
            result = sr.ReadToEnd();
        }
    }
}
Fredy
  • 532
  • 3
  • 11