我使用seven.zip.sharp来压缩流。然后,我想在压缩完成后,将内存流中的数据保存到文件流中。该文件是一个".7z"文件。
问题:
输出文件已损坏,我无法手动解压缩。使用notepad++,我也无法看到通常在7zip文件中找到的标题。
这是代码:
//Memory stream used to store compressed stream
public System.IO.Stream TheStream = new System.IO.MemoryStream();
//Start compress stream
private void button1_Click(object sender, EventArgs e)
{
Thread newThread1 = new Thread(this.COMP_STREAM);
newThread1.Start();
}
//See size of stream on demand
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.Text += "-" + TheStream.Length;
}
//To Create file
private void button3_Click(object sender, EventArgs e)
{
byte[] buffer = new byte[1024]; // Change this to whatever you need
using (System.IO.FileStream output = new FileStream(@"F:Pasta desktopsssTESTEmiau.7z", FileMode.Create))
{
int readBytes = 0;
while ((readBytes = TheStream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, readBytes);
}
output.Close();
}
MessageBox.Show("DONE");
}
//To compress stream
public void COMP_STREAM()
{
SevenZip.SevenZipCompressor.SetLibraryPath(@"C:Program Files7-Zip7z.dll");
var stream = System.IO.File.OpenRead(@"F:Pasta desktopssslel.exe");
SevenZip.SevenZipCompressor compressor = new SevenZip.SevenZipCompressor();
compressor.CompressionMethod = SevenZip.CompressionMethod.Lzma2;
compressor.CompressionLevel = SevenZip.CompressionLevel.Ultra;
compressor.CompressStream(stream, TheStream); //I know i can just use a FileStream here but i am doing this from testing only.
MessageBox.Show("Done");
}
请有人把这个问题改一下,使它看起来更好。如果你愿意,可以加上更好的标题。非常感谢。
因此,您计划将压缩流存储在临时MemoryBuffer中,然后将其写入文件。问题是写入后必须重置MemoryStream,因此读取操作从一开始就读取。如果您的输出文件大小为0,那么我确信这就是问题所在。
这里有一个修复:
// Seek the beginning of the `MemoryStrem` before writing it to a file:
TheStream.Seek(0, SeekOrigin.Begin);
或者,您可以将流声明为MemoryStream
,并使用Position
属性:
TheStream.Position = 0;