基本上我正在尝试将文件“sample.doc”压缩为.gz文件格式。当发生这种情况时,会告诉它删除文件的扩展名,而不是显示为 “sample.doc.gz”它显示为“sample.gz”。但是,当提取文件时,它也丢失了“.doc”文件扩展名。例如。文件名只是“样本”。有什么想法吗?
使用System; 使用System.IO; 使用System.IO.Compression; 使用System.Text;
命名空间gzipexample {
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();
}
}
}
答案 0 :(得分:1)
如果我正确理解你的问题,就没有解决方案。一个gzip的文件(至少,一个文件gzip'你正在做的方式)不存储它的名字,所以如果压缩一个名为sample.doc的文件,输出名为sample.gz,那么“ .doc“部分永远消失了。这就是为什么如果使用gzip命令行实用程序压缩文件,它就是压缩版本sample.doc.gz。
在某些受限情况下,您可以通过查看文件的内容来猜测适当的扩展名,但这不是很可靠。如果您只需要压缩,并且文件格式不受约束,您可以只构建一个.zip文件,它会存储文件名。