使用ZipFile.ExtractToFile方法,并将overwrite参数设置为true,这样可以覆盖同名的目标文件。代码如下:
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string zipPath = @"c:\example\start.zip";
string extractPath = @"c:\example\extract";
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
entry.ExtractToFile(Path.Combine(extractPath, entry.FullName), true);
}
}
}
}
}
使用ZipFile.ExtractToDirectory方法,将zip文件解压到一个临时文件夹,然后检查解压后的文件是否在目标文件夹中已存在,如果是,则删除已存在的文件,并将新解压的文件移动到目标文件夹¹。代码如下
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string zipPath = @"c:\example\start.zip";
string extractPath = @"c:\example\extract";
//Declare a temporary path to unzip your files
string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
ZipFile.ExtractToDirectory(zipPath, tempPath);
//build an array of the unzipped files
string[] files = Directory.GetFiles(tempPath);
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath,f.Name)))
{
File.Delete(Path.Combine(extractPath, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
}
//Delete the temporary directory
Directory.Delete(tempPath, true);
}
}
}