Search code examples
.netvb.netvisual-studiozipdotnetzip

Can I ReadAllLines from a zipped txt file without extracting?


Is it possible to use System.IO.File.ReadAllLines on a zipped txt file without extracting it?

I found a few solutions that include extracting and deleting the file, but I would really prefer to avoid this solution.


Solution

  • here is a console app that should point you on your way:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.IO.Compression;
    
    namespace ZipExploration
    {
    class Program
    {
        static void Main(string[] args)
        {
            getFileList(@"C:\errors\myfiles.zip");
            Console.ReadLine();
        }
    
        static List<string> getFileList(string zip)
        {
                List<string> retVal = new List<string>();
            try
            {
    
                if (!File.Exists(zip))
                {
                    Console.WriteLine(@"File does not exist");
                }
    
                //FileInfo fi = new FileInfo(zip);
                //using (MemoryStream ms = new MemoryStream())
                using( FileStream ms = File.Create(@"C:\Errors\myfile.txt"))
                {
                    using (FileStream fs = new FileStream(zip,FileMode.Open))
                    {
                        using (ZipArchive arc = new ZipArchive(fs,ZipArchiveMode.Read))
                        {
                            foreach (ZipArchiveEntry e in arc.Entries)
                            {                               
                                retVal.Add(e.FullName);
                                Console.WriteLine(e.FullName);
                                getContents(e);
                            }
                        }
                    }
                    ms.Close();
                    //byte[] buffer = ms.ToArray();
                    //Console.WriteLine(buffer.Length);
                    //Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
    
            return retVal;
    
        }
    
        static void getContents(ZipArchiveEntry e)
        {
            using (StreamReader stm = new StreamReader( e.Open()))
            {
                Console.WriteLine(stm.ReadToEnd());
            }
        }
    }
    

    }