【问题标题】:Zip download and extract exceptionZip 下载和解压异常
【发布时间】:2021-03-11 20:34:48
【问题描述】:

所以我正在尝试做 - 从 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)
        {

        }
    }
}

【问题讨论】:

  • 在开始过程之前添加所有事件处理程序。提供完整路径而不是这些内容:@".\new_ver.zip" 等(部署时,您将不知道该文件将在哪里结束)。检查相同的文件是否已经存在,并询问用户是否应该替换、复制或中止操作。
  • await DownloadFileAsync 或者你可以使用非异步的DownloadFile。虽然我不明白你为什么将它下载到文件然后压缩它。您可以通过流下载并随时压缩流
  • @Charlieface 你不能等待DownloadFileAsync

标签: c# webclient


【解决方案1】:

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

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

ZipFile.ExtractToDirectory(zipPath, extractPath, true);

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      相关资源
      最近更新 更多