我的zip文件替换现有文件时出现问题。我已经看过这里的其他例子了,我似乎无法弄明白......
我有一个loop
,它将提取的文件的一些统计信息写入文本框。我认为就是这一行:
if (!System.IO.File.Exists(fileUnzipFullName))
我的代码:
public void UnzipFileNew()
{
richTextBox1.AppendText("\r\n" + "EXTRACTING!");
String rootpath = Environment.CurrentDirectory;
//This stores the path where the file should be unzipped to,
//including any subfolders that the file was originally in.
string fileUnzipFullPath;
//This is the full name of the destination file including
//the path
string fileUnzipFullName;
//Opens the zip file up to be read
using (ZipArchive archive = ZipFile.OpenRead(@"update.zip"))
{
//Loops through each file in the zip file
foreach (ZipArchiveEntry file in archive.Entries)
{
//Outputs file information to the Textbox
richTextBox1.AppendText("\r\n");
richTextBox1.AppendText("File Name: "+ file.Name);
richTextBox1.AppendText("\r\n");
richTextBox1.AppendText("File Size: bytes "+ file.Length);
richTextBox1.AppendText("\r\n");
richTextBox1.AppendText("Compression Ratio: "+ ((double)file.CompressedLength / file.Length).ToString("0.0%"));
richTextBox1.AppendText("\r\n");
//Identifies the destination file name and path
fileUnzipFullName = Path.Combine(rootpath, file.FullName); //fileUnzipFullName = Path.Combine(@"Example\", file.FullName);
//Extracts
if (!System.IO.File.Exists(fileUnzipFullName))
{
fileUnzipFullPath = Path.GetDirectoryName(fileUnzipFullName);
//Creates the directory if it doesn't exist
Directory.CreateDirectory(fileUnzipFullPath);
//Extracts the file to (potentially new) path
file.ExtractToFile(fileUnzipFullName);
}
}
}
}
答案 0 :(得分:1)
if (!System.IO.File.Exists(fileUnzipFullName))
确实会阻止您尝试提取文件。因此,您需要将其删除或根据您的使用情况进行更改。
此外,如果文件已经存在,ExtractToFile
方法将抛出IOException
。幸运的是,MSDN显示有一个带有布尔标志的重载用于覆盖:
public static void ExtractToFile(
this ZipArchiveEntry source,
string destinationFileName,
bool overwrite
)
所以而不是
file.ExtractToFile(fileUnzipFullName);
使用
file.ExtractToFile(fileUnzipFullName, true);
使用你的代码,这将不加区别地用从zip中提取的文件覆盖所有文件:
//Extracts
//if (!System.IO.File.Exists(fileUnzipFullName))
//{
fileUnzipFullPath = Path.GetDirectoryName(fileUnzipFullName);
//Creates the directory if it doesn't exist
Directory.CreateDirectory(fileUnzipFullPath);
//Extracts the file to (potentially new) path
file.ExtractToFile(fileUnzipFullName, true);
//}