压缩和解压

ZipFile.CreateFromDirectory("logs", "logs3.zip");
ZipFile.ExtractToDirectory("logs3.zip", "logs3");

正斜杠和反斜杠 forward slash (“/”) and backslash (“")

For apps that target the .NET Framework 4.6.1 and later versions, the path separator character has changed from a backslash (“") to a forward slash (“/”) in the FullName property of ZipArchiveEntry objects created by overloads of the CreateFromDirectory method. The change brings the .NET implementation into conformity with section 4.4.17.1 of the .ZIP File Format Specification and allows .ZIP archives to be decompressed on non-Windows systems.

<runtime>
<AppContextSwitchOverrides value="Switch.System.IO.Compression.ZipFile.UseBackslash=false" />
</runtime>

zenon

<?xml version=”1.0” encoding=”utf-8” ?>

ZipFileUseBackslash

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
    <AppContextSwitchOverrides value="Switch.System.IO.Compression.ZipFile.UseBackslash=false" />
    <generatePublisherEvidence enabled="false"/>
</runtime>
</configuration>

日志文件夹

修复反斜杠空文件夹造成的zip文件读取错误

当使用zip压缩时,有可能因为环境的不同而造成使用的路径分割符不同,按照标准,应该使用正斜杠/,而不是使用反斜杠。下面两张图显示的是zip文件中的文件名称,第一张使用了反斜杠,第二张使用的是正斜杠

日志文件夹
日志文件夹

可以在使用反斜杠时,对空的文件夹的目录下再添加一个空的“readme.txt”文件,解决读取错误。

using (ZipArchive za = ZipFile.Open(pMPPPackagePath, ZipArchiveMode.Update))
{
    List<ZipArchiveEntry> emptyFolders = (from ZipArchiveEntry zae in za.Entries
                                            //where zae.FullName.EndsWith("/") || zae.FullName.EndsWith("\\")
                                            where zae.FullName.EndsWith("\\")
                                            select zae).ToList<ZipArchiveEntry>();

    LogService.WriteLog(TraceEventType.Information, "Add Readme.txt to fix use Backslash as path separator character issue.");
    foreach (ZipArchiveEntry zae in emptyFolders)
    {
        LogService.WriteLog(TraceEventType.Information, zae.FullName);
    }

    emptyFolders.ForEach((ZipArchiveEntry folder) => folder.Delete());
    emptyFolders.ForEach((ZipArchiveEntry folder) => za.CreateEntry(folder.FullName + "Readme.txt"));

    //ZipArchiveEntry readmeEntry = za.CreateEntry("Readme.txt");
    //using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
    //{
    //    writer.WriteLine("Backslash");
    //}
}