Using .NET ZipArchive to zip entire directories AS well as extra info

こ雲淡風輕ζ 提交于 2019-12-12 03:24:45

问题


I inherited some code that makes use of ZipArchive to save some information from the database. It uses BinaryFormatter to do this. When you look at the zip file with 7-zip (for example), you see a couple of folders and a .txt file. All is working well. I simply want to modify the code to also have a folder in the ZipArchive called "temp" that consists of files and folders under C:\temp. Is there an easy way to add a entry (ZipArchiveEntry?) that consist of an entire folder or the disc? I saw "CreateEntryFromFile" in the member methods of ZipArchive, but no CreateEntryFromDirectory. Or perhaps there's some other simple way to do it? Anyone have example code? I should say that C:\temp could have variable number of files and directories (that have child directories and files, etc.) Must I enumerate them somehow, create my own directories use CreateEntryFromFile? Any help is appreciated.

Similarly, when I read the ZipArchive, I want to take the stuff related to C:\temp and just dump it in a directory (like C:\temp_old) Thanks, Dave


回答1:


The answer by user1469065 in Zip folder in C# worked for me. user1469065 shows how to get all the files/directories in the directory (using some cool "yield" statements) and then do the serialization. For completeness, I did add the code to deserialize as user1469065 suggested (at least I think I did it the way he suggested).

private static void ReadTempFileStuff(ZipArchive archive) // adw
    {
        var sessionArchives = archive.Entries.Where(x => x.FullName.StartsWith(@"temp_directory_contents")).ToArray();
        if (sessionArchives != null && sessionArchives.Length > 0)
        {
            foreach (ZipArchiveEntry entry in sessionArchives)
            {
                FileInfo info = new FileInfo(@"C:\" + entry.FullName);
                if (!info.Directory.Exists)
                {
                    Directory.CreateDirectory(info.DirectoryName);
                }
                entry.ExtractToFile(@"C:\" + entry.FullName,true);
            }
        }
    }


来源:https://stackoverflow.com/questions/36872218/using-net-ziparchive-to-zip-entire-directories-as-well-as-extra-info

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!