C#压缩文件操作如何进行
导读:在C#中,可以使用System.IO.Compression命名空间中的类来进行文件的压缩和解压缩操作。具体来说,可以使用ZipArchive类来创建和打开ZIP文件,并使用ZipFile类来实现文件的压缩和解压缩。 以下是一个简单的示例代...
在C#中,可以使用System.IO.Compression命名空间中的类来进行文件的压缩和解压缩操作。具体来说,可以使用ZipArchive类来创建和打开ZIP文件,并使用ZipFile类来实现文件的压缩和解压缩。
以下是一个简单的示例代码,演示如何使用ZipFile类来进行文件的压缩和解压缩操作:
using System;
using System.IO;
using System.IO.Compression;
class Program
{
static void Main()
{
string sourceFile = @"C:\example.txt";
string compressedFile = @"C:\example.zip";
string decompressedFile = @"C:\decompressed.txt";
// 压缩文件
using (FileStream fs = new FileStream(compressedFile, FileMode.Create))
{
using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Create))
{
archive.CreateEntryFromFile(sourceFile, Path.GetFileName(sourceFile));
}
}
Console.WriteLine("文件已成功压缩为: " + compressedFile);
// 解压缩文件
using (ZipArchive archive = ZipFile.OpenRead(compressedFile))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
entry.ExtractToFile(decompressedFile, true);
}
}
Console.WriteLine("文件已成功解压为: " + decompressedFile);
}
}
在上面的示例代码中,首先创建了一个ZipArchive对象来表示要压缩的文件,然后调用CreateEntryFromFile方法将源文件添加到压缩文件中。接着使用ZipFile类的OpenRead方法打开压缩文件,并通过遍历ZipArchive对象的Entries属性来将压缩文件中的文件解压缩到指定路径下。
请注意,要使用以上代码示例,需要在项目中添加对System.IO.Compression命名空间的引用。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: C#压缩文件操作如何进行
本文地址: https://pptw.com/jishu/688038.html