简体   繁体   中英

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. It's working for the most part, but the file is losing 27 kb of data. 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.

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.

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