如何解压缩.gz文件并使用c#?
将文件保存在特定文件夹中这是我第一次遇到.gz文件。我已经在搜索如何解压缩但它对我不起作用。它没有解压缩特定文件夹中的.gz文件。我不想使用任何第三方应用程序。
任何人都可以给我一个关于如何解压缩它的示例代码。然后将文件保存在文件夹中。感谢。
答案 0 :(得分:20)
MSDN中的以下示例显示了如何使用GZipStream类压缩和解压缩文件目录。
namespace zip
{
public class Program
{
public static void Main()
{
string directoryPath = @"c:\users\public\reports";
DirectoryInfo directorySelected = new DirectoryInfo(directoryPath);
foreach (FileInfo fileToCompress in directorySelected.GetFiles())
{
Compress(fileToCompress);
}
foreach (FileInfo fileToDecompress in directorySelected.GetFiles("*.gz"))
{
Decompress(fileToDecompress);
}
}
public static void Compress(FileInfo fileToCompress)
{
using (FileStream originalFileStream = fileToCompress.OpenRead())
{
if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fileToCompress.Name, fileToCompress.Length.ToString(), compressedFileStream.Length.ToString());
}
}
}
}
}
public static void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
}
}
}
}
}
}
答案 1 :(得分:7)
.Net有GZipStream
API中列出的示例...
public static void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
}
}
}
}
答案 2 :(得分:0)
以下链接显示了两个用于压缩和解压缩到C#中文件的示例。您可以使用此示例。
样品(使用7-zip):
var tmp = new SevenZipCompressor();
tmp.ScanOnlyWritable = true;
tmp.CompressFilesEncrypted(outputFilePath, password, filePaths);
示例(使用ZipArchive):
ZipArchive zip = ZipFile.Open(filePath, ZipArchiveMode.Create);
zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
zip.Dispose();
了解更多信息:
http://csharpexamples.com/zip-and-unzip-files-programmatically-in-c/