Zip 下载和提取异常

问题描述

所以我想要做的是 - 从 URI 下载 zip 文件,并将其解压缩到某个目录中,但我收到此错误

"System.IO.IOException: "文件 'C:\Users\yup_c\source\repos\LauncherYCFPS\bin\Debug\net5.0-windows\new_ver.zip' 已经存在。"

所以我认为它是由 wc.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFinished); 引起的,因为它没有正常工作,static void DownloadFinished(object sender,EventArgs e) 没有等待文件下载就启动了,我哪里出错了?

using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Data;
using System.Net;
using System.Windows.Forms;
using System.ComponentModel;

namespace LauncherYCFPS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender,EventArgs e)
        {
            {
                using (WebClient wc = new WebClient())
                {
                    wc.DownloadProgressChanged += wc_DownloadProgressChanged;
                    wc.DownloadFileAsync(
                        // Param1 = Link of file
                        new System.Uri("http://o997388w.beget.tech/new_ver.zip"),// Param2 = Path to save
                        @".\new_ver.zip"
                    ) ;
                    wc.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFinished);
                }
                static void DownloadFinished(object sender,EventArgs e)
                {
                    string startPath = @".\";
                    string zipPath = @".\new_ver.zip";
                    string extractPath = @".\extract";

                    ZipFile.CreateFromDirectory(startPath,zipPath);

                    ZipFile.ExtractToDirectory(zipPath,extractPath);
                }
            }
            // Event to track the progress
            void wc_DownloadProgressChanged(object sender,DownloadProgressChangedEventArgs e)
            {
                progressBar1.Value = e.Progresspercentage;
            }
        }

        private void Form1_Load(object sender,EventArgs e)
        {

        }
    }
}

解决方法

看错误,已经有同名文件了!

您必须在使用 ZipFile.ExtractToDirectory 方法之前删除目录或使用该方法,这将覆盖现有目录:

ZipFile.ExtractToDirectory(zipPath,extractPath,true);
,

使用允许您覆盖文件的重载:

public static void ExtractToDirectory (string sourceArchiveFileName,string destinationDirectoryName,System.Text.Encoding? entryNameEncoding,bool overwriteFiles);