简体   繁体   中英

How to work with a ZipArchive in C#

I have a ZipArchive and am looking to access a file inside. I am not sure how I would do this, but I have a list

List<ZipContents> importList = new List<ZipContents>();

Which has two parameters:

  1. ZipArchive which is called ZipFile
  2. String which is called FileName

Inside the ZipArchive which is importList.ZipFile I need to find an XML file that has the same name as the Zip file name.

Currently I have this:

foreach (var import in importList)
{
    var fn = import.FileName; // This is the actual file name of the zip file 
    // that was added into the ZipArchive. 
    // I will need to access the specific XML file need in the Zip by associating with
    // fn

    // ToDo: Extract XML file needed 
    // ToDo: Begin to access its contents...

}

So for example the code is looking into the ZipArchive with the name test.zip . there will be a file called test.xml that I will then need to be able to access its contents.

Like I said above I need to be able to access the contents of that file. I am sorry I have no code to support how to do this, but I have not been able to find anything else...

I have looked through a lot of the ZIpArchive documentation (including: http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive%28v=vs.110%29.aspx ) and other posts on SO on how to do this, but I have come up empty. Would anyone have an idea on how to do this? Any help would be much appreciated. Thanks!

You need to extract the archive to a directory (may as well use temp since I assume you don't want to keep these):

archive.ExtractToDirectory("path string");

//Get the directory info for the directory you just extracted to
DirectoryInfo di = new DirectoryInfo("path string");

//find the xml file you want
FileInfo fi = di.GetFiles(string.Format("{0}.xml", archiveName)).FirstOrDefault();

//if the file was found, do your thing
if(fi != null)
{
    //Do your file stuff here.
}

//delete the extracted directory
di.Delete();

Edit: To do the same thing just unpacking the file you care about:

//find your file
ZipArchiveEntry entry = archive
                         .Entries
                         .FirstOrDefault(e => 
                             e.Name == string.Format("{0}.xml", archiveName));

if(entry != null)
{
   //unpack your file
   entry.ExtractToFile("path to extract to");

   //do your file stuff here
}

//delete file if you want

The MSDN you linked does a rather good job explaining how to access the files. Here it is applied to your example.

// iterate over the list items
foreach (var import in importList)
{
    var fn = import.FileName;

    // iterate over the actual archives
    foreach (ZipArchiveEntry entry in import.ZipFile.Entries)
    {
        // only grab files that end in .xml
        if (entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
        {
            // this extracts the file
            entry.ExtractToFile(Path.Combine(@"C:\extract", entry.FullName));

            // this opens the file as a stream
            using(var stream = new StreamReader(entry.Open())){
                // this opens file as xml stream
                using(var xml = XmlReader.Create(stream){
                    // do some xml access on an arbitrary node
                    xml.MoveToContent();
                    xml.ReadToDescendant("my-node");
                    var item = xml.ReadElementContentAsString();
                }
            }
        }
    }
}

The following will extract a single xml file called file.xml and read it to an XDocument object:

var xmlEntry = importList.SelectMany(y => y.Entries)
                         .FirstOrDefault(entry => entry.Name.Equals("file.xml",
                                                  StringComparison.OrdinalIgnoreCase));
if (xmlEntry == null)
{
    return;
}

// Open a stream to the underlying ZipArchiveEntry
using (XDocument xml = XDocument.Load(xmlEntry.Open()))
{
    // Do stuff with XML
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM