Has*_*sef -1 c# ziparchive .net-core asp.net-core
我有以下代码,即create一个新的zip文件,然后add entry使用NoCompressionie 将该文件压缩到该文件,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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
zip文件及其条目均已创建,我可以从Windows资源管理器中访问它们,但是一旦代码尝试读取它,它将得到以下错误:
未处理的异常:System.IO.DirectoryNotFoundException:找不到路径'd:\ release.zip \ Readme.txt'的一部分。在System.IO.Win32FileSystem.Open(String fullPath,FileMode模式,FileAccess访问权限,在System.IO.Win32FileStream..ctor(字符串路径,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize,FileOptions选项,FileStream父目录) System.IO.FileStream.Init(字符串路径,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize,FileOptions选项)位于System.IO.File.InternalReadAllText(字符串)处的FileShare共享,Int32 bufferSize,FileOptions选项,FileStream父级路径,编码编码)
位于ConsoleApplication.Program.Main(String [] args)的System.IO.File.ReadAllText(String路径)
首先要注意的是,您没有创建zip文件,而是创建了具有特定压缩率的存档文件。在您的情况下,您创建了一个没有压缩的ZIP存档。
我可以从Windows资源管理器中访问它们
我不能,因为我有与.zip文件关联的7zip ,所以7z会打开存档。在您的情况下,Windows资源管理器正在为您执行此操作。因此,当您浏览.zip并打开文件时,资源管理器会将存档文件视为文件夹,并向您显示存档的内容。
但是,当您这样做时:
string text = System.IO.File.ReadAllText(@"d:\release.zip\Readme.txt");
Run Code Online (Sandbox Code Playgroud)
System.IO.File.ReadAllText将打开您作为参数传递的特定文件,在您的情况下为d:\release.zip\Readme.txt。因此,尝试打开的路径是:drive D:,folder release.zip,file Readme.txt... ... d:\release.zip是文件而不是文件夹,因此找不到该路径,这就是为什么您要获取DirectoryNotFoundException异常的原因。
为了这一点,如果你想读的条目,只是做你所做的事Create存档,除了Read从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);
Run Code Online (Sandbox Code Playgroud)
希望能对您有所帮助。
| 归档时间: |
|
| 查看次数: |
565 次 |
| 最近记录: |