Pergunta

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.

Foi útil?

Solução

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());
        }
    }
}

}

Outras dicas

You can do it with BoxedApp SDK to create a virtual directory and extract the contents of the zip file to that directory. No files would be written on disk. There is also NI.Vfs library, but I have not used it.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top