【问题标题】:c# gzip - keep extension on original file but remove when compressingc# gzip - 保留原始文件的扩展名,但在压缩时删除
【发布时间】:2011-05-03 04:54:13
【问题描述】:

基本上,我正在尝试将文件“sample.doc”压缩为 .gz 文件格式。发生这种情况时,系统会告诉它删除文件的扩展名,而不是显示为 “sample.doc.gz”显示为“sample.gz”。但是,当文件被提取时,它也丢失了它的“.doc”文件扩展名。例如。文件名只是“样本”。有什么想法吗?

使用系统; 使用 System.IO; 使用 System.IO.Compression; 使用 System.Text;

命名空间 gzip 示例 {

class Program
{
    public static void Main()
    {
        CompressFile(@"C:\sample.doc");
   }


    //Compresses the file into a .gz file
    public static void CompressFile(string path)
    {
        string compressedPath = path;
        Console.WriteLine("Compressing: " + path);

        int extIndex = compressedPath.LastIndexOf(".");
        FileStream sourceFile = File.OpenRead(path);
        FileStream destinationFile = File.Create(compressedPath.Replace(compressedPath.Substring(extIndex), "") + ".gz");

        byte[] buffer = new byte[sourceFile.Length];

        sourceFile.Read(buffer, 0, buffer.Length);

        using (GZipStream output = new GZipStream(destinationFile,
            CompressionMode.Compress))
        {
            Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name,
                destinationFile.Name, false);

            output.Write(buffer, 0, buffer.Length);
        }

        // Close the files.
        sourceFile.Close();
        destinationFile.Close();
    }
}

}

【问题讨论】:

    标签: c# gzip filenames compression


    【解决方案1】:

    如果我正确理解了您的问题,则说明没有解决方案。一个 gzip'ed 文件(至少,一个 gzip'ed 文件)不存储它的名称,所以如果你压缩一个名为 sample.doc 的文件并且输出名为 sample.gz,“ .doc”部分永远消失了。这就是为什么如果您使用 gzip 命令行实用程序压缩文件,它是压缩版本 sample.doc.gz。

    在某些受限的情况下,您可能可以通过查看文件的内容来猜测适当的扩展名,但这不是很可靠。如果您只需要压缩,并且文件格式不受限制,则可以只构建一个 .zip 文件,它会存储文件名。

    【讨论】:

    • 我可以使用另一种方法来存储文件名吗?
    • 假设你同时控制压缩和解压工具,有多种解决方案:例如,你可以将文件名写在文件的开头,然后在你的解压中解压出来工具。或者你可以写出一个 .zip 文件。
    • 你有没有机会给我看一个 .zip 方法的例子?我尝试更改为 .gz 仍然无法正常工作。我也不会为此解压缩文件,所以我无法这样做。
    • 如果不是你控制的工具,你到底用什么来解压文件?
    • 哦...好吧,dotnetzip.codeplex.com 是一个可以编写 .zip 文件的库。
    猜你喜欢
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多