从“Zip”文件中以“零”压缩比读取文件文本

问题描述 投票:0回答:1

我有下面的代码,即

create
一个新的 zip 文件,然后
add entry
使用
NoCompression
到此文件,即
ZERO compression ratio
,然后尝试将此条目作为普通文本读取。

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            using (FileStream zipToOpen = new FileStream(@"d:\release.zip", FileMode.Create))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt", CompressionLevel.NoCompression);
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                    {
                            writer.WriteLine("Information about this package.");
                            writer.WriteLine("========================");
                    }
                }
            }

           string text = System.IO.File.ReadAllText(@"d:\release.zip\Readme.txt");
           Console.WriteLine("Contents of WriteText.txt = {0}", text);
        }
    }
}

zip 文件及其条目都已创建,我可以从 Windows 资源管理器访问它们,但是一旦代码尝试读取它,就会出现以下错误:

未处理的异常:System.IO.DirectoryNotFoundException:无法 找到路径 'd 的一部分: elease.zip\Readme.txt'。在 System.IO.Win32FileStream..ctor(字符串路径、FileMode模式、FileAccess 访问、FileShare 共享、Int32 bufferSize、FileOptions 选项、 FileStream 父级)位于 System.IO.Win32FileSystem.Open(String fullPath、FileMode 模式、FileAccess 访问、FileShare 共享、Int32 bufferSize、FileOptions 选项、FileStream 父级)位于 System.IO.FileStream.Init(字符串路径、FileMode模式、FileAccess 访问、FileShare 共享、Int32 bufferSize、FileOptions 选项)位于 System.IO.File.InternalReadAllText(字符串路径,Encoding编码)
在 System.IO.File.ReadAllText(字符串路径)处 ConsoleApplication.Program.Main(String[] args)

c# asp.net-core .net-core c#-ziparchive
1个回答
4
投票

首先应该注意的是,您没有创建 zip 文件,而是创建了具有特定压缩的存档文件;就您而言,您创建了一个未压缩的 ZIP 存档。

我可以从 Windows 资源管理器访问它们

我不能,因为我有 7zip 与

.zip
文件关联,所以 7z 打开存档;在您的情况下,Windows 资源管理器正在为您执行此操作。因此,当您浏览到
.zip
文件并打开它时,资源管理器会将存档文件视为文件夹,并向您显示存档的内容。

但是,当您这样做时:

string text = System.IO.File.ReadAllText(@"d:\release.zip\Readme.txt");

System.IO.File.ReadAllText
将打开您作为参数传递的特定文件,在您的情况下为
d:\release.zip\Readme.txt
。因此尝试打开的路径是:驱动器
D:
,文件夹
release.zip
,文件
Readme.txt
...由于
d:\release.zip
文件而不是文件夹,因此无法找到路径,即为什么您会遇到
DirectoryNotFoundException
异常。

为此,如果您想阅读该条目,只需对

Create
存档执行相同操作,除了
Read
'ed 存档中的
Open
.GetEntry
而不是
.CreateEntry
,例如:

string text = string.Empty;
using (FileStream zipToOpen = new FileStream(@"c:\test\release.zip", FileMode.Open)) {
    using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read)) {
        ZipArchiveEntry readmeEntry = archive.GetEntry("Readme.txt");
        using (StreamReader reader = new StreamReader(readmeEntry.Open())) {
            text = reader.ReadToEnd();
        }
    }
}
Console.WriteLine("Contents of WriteText.txt = {0}", text);

希望能有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.