C# List of files in an archive

ε祈祈猫儿з 提交于 2020-01-02 08:21:52

问题


I am creating a FileFinder class, where you can do a search like this:

    var fileFinder = new FileFinder(
                         new string[]
                             {
                                  "C:\\MyFolder1",
                                  "C:\\MyFolder2" 
                             }, 
                         new string[]
                             {
                                  "*.txt",
                                  "*.doc"
                             } );
    fileFinder.FileFound += new EventHandler<FileFinderEventArgs>(FileFinder_FileFound);
    DoSearch();

If I executed that code, FileFinder_FileFound would be called every time a *.txt or *.doc file was found in C:\\MyFolder1 and its subfolders, or C:\\MyFolder2 and its subfolders.

Sot the class looks through subfolders, but I also want it to look through any zip files it comes across, as if they were folders. How can I do this? It would be preferable that no temporary files be created...

EDIT Forgot to mention this is not a personal project; its for a commercial application I'm working on with my company.


回答1:


Checkout System.IO.Packaging Namespace available in .NET 3.5 and higher. You'll find some good answers here




回答2:


You should use a tool like SharpZipLib: http://www.icsharpcode.net/opensource/sharpziplib/. This allows you to list the files in a .zip file and, optionally extract them.

The .NET framework does not natively support using the FileFinder to search in .zip files.




回答3:


If you can use .NET 4.5 or higher you can now finally use ZipArchive. It's in the System.IO.Compression namespace. The example uses ZipFile class too, which requires not just referencing System.IO.Compression assembly, but System.IO.Compression.FileSystem assembly too (both contribute to the same namespace). MSDN: http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive%28v=vs.110%29.aspx

So if your finder encounter a zip file, you can do something like this (the gist of it):

using System;
using System.IO;
using System.IO.Compression;

using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
{
    foreach (ZipArchiveEntry entry in archive.Entries)
    {
        if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) ||
            entry.FullName.EndsWith(".doc", StringComparison.OrdinalIgnoreCase))
        {
            // FileFinder_FileFound(new FileFinderEventArgs(...))
        }
    }
}


来源:https://stackoverflow.com/questions/4069092/c-sharp-list-of-files-in-an-archive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!