简体   繁体   English

C#ZipArchive丢失数据

[英]C# ZipArchive losing data

I'm trying to copy the contents of one Excel file to another Excel file while replacing a string inside of the file on the copy. 我正在尝试将一个Excel文件的内容复制到另一个Excel文件,同时替换副本中文件内部的字符串。 It's working for the most part, but the file is losing 27 kb of data. 它在大多数情况下都可以正常工作,但是文件丢失了27 kb的数据。 Any suggestions? 有什么建议么?

public void ReplaceString(string what, string with, string path) {
    List < string > doneContents = new List < string > ();
    List < string > doneNames = new List < string > ();
    using(ZipArchive archive = ZipFile.Open(_path, ZipArchiveMode.Read)) {
        int count = archive.Entries.Count;
        for (int i = 0; i < count; i++) {
            ZipArchiveEntry entry = archive.Entries[i];

            using(var entryStream = entry.Open())
            using(StreamReader reader = new StreamReader(entryStream)) {
                string txt = reader.ReadToEnd();
                if (txt.Contains(what)) {
                    txt = txt.Replace(what, with);
                }
                doneContents.Add(txt);
                string name = entry.FullName;
                doneNames.Add(name);
            }
        }
    }

    using(MemoryStream zipStream = new MemoryStream()) {
        using(ZipArchive newArchive = new ZipArchive(zipStream, ZipArchiveMode.Create, true, Encoding.UTF8)) {
            for (int i = 0; i < doneContents.Count; i++) {
                int spot = i;
                ZipArchiveEntry entry = newArchive.CreateEntry(doneNames[spot]);

                using(var entryStream = entry.Open())
                using(var sw = new StreamWriter(entryStream)) {
                    sw.Write(doneContents[spot]);
                }
            }
        }

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

I've used Microsoft's DocumentFormat.OpenXML and Excel Interop, however, they are both lacking in a few main components that I need. 我使用了Microsoft的DocumentFormat.OpenXML和Excel Interop,但是它们都缺少一些我需要的主要组件。

Update: 更新:

using(var fileStream = new FileStream(path, FileMode.Create)) {
    var wrapper = new StreamWriter(fileStream);
    wrapper.AutoFlush = true;
    zipStream.Seek(0, SeekOrigin.Begin);
    zipStream.CopyTo(wrapper.BaseStream);
    wrapper.Flush();
    wrapper.Close();
}

Try the process without changing the string and see if the file size is the same. 在不更改字符串的情况下尝试该过程,并查看文件大小是否相同。 If so then it would seem that your copy is working correctly, however as Marc B suggested, with compression, even a small change can result in a larger change in the overall size. 如果是这样,则您的副本似乎可以正常工作,但是正如Marc B建议的那样,压缩后,即使很小的更改也可能导致整体大小的较大更改。

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

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