问题描述
我想使用 SevenZipSharp 压缩一个字符串,并使用以下代码拼凑了一个 C# 控制台应用程序(我是 C# 的新手)(其中的点点滴滴来自 SO 上的类似问题).
I'd like to compress a string using SevenZipSharp and have cobbled together a C# console application (I'm new to C#) using the following code, (bits and pieces of which came from similar questions here on SO).
压缩部分似乎可以工作(尽管我传递的是文件而不是字符串),压缩字符串到控制台的输出看起来像乱码,但我卡在解压中......
The compress part seems to work (albeit I'm passing in a file instead of a string), output of the compressed string to the console looks like gibberish but I'm stuck on the decompress...
我正在尝试做与这里相同的事情(我认为):
I'm trying to do the same thing as here (I think):
https://stackoverflow.com/a/45861659/3451115
https://stackoverflow.com/a/36331690/3451115
感谢任何帮助,理想情况下,控制台将显示压缩字符串,然后是解压缩字符串.
Appreciate any help, ideally the console will display the compressed string followed by the decompressed string.
谢谢:)
using System;
using System.IO;
using SevenZip;
namespace _7ZipWrapper
{
public class Program
{
public static void Main()
{
SevenZipCompressor.SetLibraryPath(@"C:Temp7za64.dll");
SevenZipCompressor compressor = new SevenZipCompressor();
compressor.CompressionMethod = CompressionMethod.Ppmd;
compressor.CompressionLevel = SevenZip.CompressionLevel.Ultra;
compressor.ScanOnlyWritable = true;
var compStream = new MemoryStream();
var decompStream = new MemoryStream();
compressor.CompressFiles(compStream, @"C:Tempa.txt");
StreamReader readerC = new StreamReader(compStream);
Console.WriteLine(readerC.ReadToEnd());
Console.ReadKey();
// works up to here... below here output to consol is: ""
SevenZipExtractor extractor = new SevenZip.SevenZipExtractor(compStream);
extractor.ExtractFile(0, decompStream);
StreamReader readerD = new StreamReader(decompStream);
Console.WriteLine(readerD.ReadToEnd());
Console.ReadKey();
}
}
}
推荐答案
压缩的结果是二进制数据——它不是一个字符串.如果您尝试将其作为字符串读取,您只会看到垃圾.这是意料之中的 - 您不应该将其视为字符串.
The result of compression is binary data - it isn't a string. If you try to read it as a string, you'll just see garbage. That's to be expected - you shouldn't be treating it as a string.
下一个问题是您试图从 compStream
读取两次,而没有先倒带"它.您从流的末尾开始,这意味着没有数据可以解压缩.如果你只是添加:
The next problem is that you're trying to read from compStream
twice, without "rewinding" it first. You're starting from the end of the stream, which means there's no data for it to decompress. If you just add:
compStream.Position = 0;
在创建提取器之前,您很可能会发现它立即起作用.您可能还需要在读取 decompStream
之前倒带它.所以你会有这样的代码:
before you create the extractor, you may well find it works immediately. You may also need to rewind the decompStream
before reading from it. So you'd have code like this:
// Rewind to the start of the stream before decompressing
compStream.Position = 0;
SevenZipExtractor extractor = new SevenZip.SevenZipExtractor(compStream);
extractor.ExtractFile(0, decompStream);
// Rewind to the start of the decompressed stream before reading
decompStream.Position = 0;
这篇关于使用 SevenZipSharp 将流解压缩为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!