我有一个ZipArchive,我正在寻找内部文件。我不知道我会怎么做,但我有一个清单
List<ZipContents> importList = new List<ZipContents>();
其中有两个参数:
ZipArchive
,名为ZipFile
String
,名为FileName
在ZipArchive
importList.ZipFile
内,我需要找到一个与Zip文件名同名的XML文件。
目前我有这个:
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...
}
例如,代码正在查看名为test.zip
的ZipArchive。将会有一个名为test.xml
的文件,然后我需要能够访问其内容。
就像我上面说过的,我需要能够访问该文件的内容。对不起,我没有代码支持如何做到这一点,但我还没有找到其他任何东西......
我已经浏览了很多关于ZIpArchive文档(包括:http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive%28v=vs.110%29.aspx)以及关于如何执行此操作的其他帖子,但我已经空了。有人会对如何做到这一点有所了解吗?任何帮助将非常感激。谢谢!
答案 0 :(得分:2)
您需要将存档提取到目录(也可以使用temp,因为我假设您不想保留这些):
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();
编辑:要做同样的事情,只需解压缩您关注的文件:
//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
答案 1 :(得分:0)
您链接的MSDN在解释如何访问文件方面做得相当不错。这里适用于您的示例。
// 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();
}
}
}
}
}
答案 2 :(得分:0)
以下内容将提取名为xml
的单个file.xml
文件并将其读取到XDocument
对象:
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
}