简体   繁体   English

在C#中以编程方式创建新条目后,会导致zip文件中“标题丢失或损坏”的原因是什么?

[英]What can cause “missing or corrupted header” in zip file after creating a new entry programatically in c#?

I am trying to create a zip file and then add 2 new entries (xml and csv file) programmatically in C#. 我正在尝试创建一个zip文件,然后在C#中以编程方式添加2个新条目(xml和csv文件)。 But I successed to write first entry, and after that for some reason it makes my zip file corrupted (more precisely it causes missing or corrupted header). 但是我成功编写了第一个条目,之后由于某种原因它使我的zip文件损坏了(更确切地说,它导致标头丢失或损坏)。

So when it tries to open already existing zip file in order to write the second entry, an exception is thrown. 因此,当它尝试打开已经存在的zip文件以写入第二个条目时,将引发异常。

Exception thrown: 抛出异常:

'System.IO.InvalidDataException' in System.IO.Compression.FileSystem.dll ("End of Central Directory record could not be found.") System.IO.Compression.FileSystem.dll中的“ System.IO.InvalidDataException”(“找不到中央目录记录的末尾。”)

    if (Path.GetExtension(fileName) == ".zip")
    {
        m_fsOutput = new FileStream(fileName, FileMode.Create);
        m_zipFile = new ZipArchive(m_fsOutput, ZipArchiveMode.Create, true);

        ZipArchiveEntry CSVentry = m_zipFile.CreateEntry(String.Format(CultureInfo.InvariantCulture, "Test{0}.csv", testCells.ElementAt(0).Test), CompressionLevel.Optimal);
        m_fsFileWriter = new StreamWriter(CSVentry.Open());
    }

This is where I initialize zip file and streamWriter for the first entry. 这是我为第一个条目初始化zip文件和streamWriter的地方。 Basically m_fsFileWriter is a type of StreamWriter and I use this object to write the file in other places. 基本上, m_fsFileWriterStreamWriter ,我使用此对象在其他位置写入文件。

I just had to do something similar a few weeks ago. 几周前我只需要做类似的事情。 The code I used was this: 我使用的代码是这样的:

List<FileStream> FilesList = new List<FileStream>();
//Add your files
using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
{
    int i = 0;
    foreach (var FileStream in FilesList)
    {
        string fileName = "File"+i;
        var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
        using (var entryStream = fileInArchive.Open())
        {

            entryStream.Flush();
            FileStream.CopyTo(entryStream);
            FileStream.Flush();

        }
        i++;
    }

}
var path = "your path";
using (var fileStream = new FileStream(path, FileMode.Create))
{
    outStream.Seek(0, SeekOrigin.Begin); 

    outStream.CopyTo(fileStream);
}

FilesList are the streams of the files you want to add to the zip archive. FilesList是要添加到zip存档中的文件流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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