GZipStream提供零字节文件

时间:2017-07-25 07:59:48

标签: c# .net filestream dotnetzip

我使用DotNetZip的GZipStream来压缩文件。我遇到的问题是生成的文件是空的。我试过冲洗/关闭流,但没有结果。任何人都知道我做错了什么:

using (var outputStream = new FileStream(path + fileName + ".gz", FileMode.Create, FileAccess.Write, FileShare.None))
{
    using (var zipStream = new GZipStream(outputStream, CompressionMode.Compress))
    {
        using (var inputStream = new FileStream(path + fileName, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            await inputStream.CopyToAsync(zipStream);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在这里工作得很好;你有一个完全可重复的例子,可能是基于这个吗?

结果:

dummy.txt:6492 bytes
Waiting for completion (don't do this in real code, ever)...
Complete
dummy.txt.gz:512 bytes

代码:

using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;

static class P
{
    static void Main()
    {

        File.WriteAllLines("dummy.txt",
            Enumerable.Range(1, 200).Select(i => "this is some contents: line " + i));

        WriteSize("dummy.txt");

        var t = Task.Run(() => DoTheThing(Environment.CurrentDirectory + "\\", "dummy.txt"));
        Console.WriteLine("Waiting for completion (don't do this in real code, ever)...");
        t.Wait();
        Console.WriteLine("Complete");
        WriteSize("dummy.txt.gz");
    }

    private static void WriteSize(string path)
    {
        var file = new FileInfo(path);
        Console.WriteLine(path + ":" + file.Length + " bytes");
    }

    async static Task DoTheThing(string path, string fileName)
    {
        using (var outputStream = new FileStream(path + fileName + ".gz", FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (var zipStream = new GZipStream(outputStream, CompressionMode.Compress))
            {
                using (var inputStream = new FileStream(path + fileName, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    await inputStream.CopyToAsync(zipStream);
                }
            }
        }
    }
}