【发布时间】: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。