【发布时间】:2014-02-19 17:20:08
【问题描述】:
开始编写一个简单的控制台应用程序,将文件下载到当前位置。出于某种原因,无论文件有多大,我使用的 WebClient 只下载 1kb 的文件(无论有多大)。我尝试将浏览器添加到标题中,我尝试添加“while (WC.IsBusy)”(我在谷歌搜索时发现的一个建议),我什至尝试将错误处理程序添加到已完成的处理程序以查看是什么继续,但这会引发“对象引用未设置为对象的实例。”。我正在把头发拉出来,我希望有人能看到我看不到的东西。
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Windows.Forms;
namespace csgocfgmakerupdater
{
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
instalwithargs(args);
}
else
{
installnoargs();
}
}
static void installnoargs()
{
Console.Clear();
Console.WriteLine("Current Folder: " + Directory.GetCurrentDirectory());
Console.WriteLine("");
Console.WriteLine("This will install the Counter-Strike: Global Offensive Config File Maker to your computer. Please select an option from the following:");
Console.WriteLine("");
Console.WriteLine("1. Install to Current Folder");
Console.WriteLine("2. Install to Custom Folder");
Console.WriteLine("3. Update Existing Installation in Current Folder");
Console.WriteLine("4. Update Existing Installation in Custom Folder");
Console.WriteLine("5. Exit");
string installcmd = Console.ReadLine();
switch (installcmd)
{
case "1":
try
{
string updurl = "http://cachefly.cachefly.net/100mb.test";//"http://elite.so/projects/cs-go-game-config-editor/CSGOCFGMKR.exe";
WebClient WC = new WebClient();
WC.DownloadProgressChanged += new DownloadProgressChangedEventHandler(WC_DownloadProgressChanged);
WC.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(WC_DownloadFileCompleted);
WC.DownloadFileAsync(new Uri(updurl), "100mb.test");
//this waits for the webclient to exit
while (WC.IsBusy) {
Console.WriteLine("Downloading Updated files...");
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.Clear();
Console.WriteLine(ex.Message);
}
break;
}
}
static void WC_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.UserState != e.Error)
{
Console.Clear();
Console.WriteLine("Update applied successfully!");
Console.ReadKey();
Environment.Exit(0);
}
else
{
MessageBox.Show(e.Error.Message);
}
}
static void WC_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.Clear();
Console.WriteLine("Downloading Updated files...");
Console.WriteLine(progperc.ToString() + "%");
}
}
}
【问题讨论】:
-
Console.ReadKey()行会发生什么?您/用户是否按下一个键然后 WebClient 超出范围? -
Webclient 错误后到达 WC.DownloadFileAsync 下的 Console.ReadKey()。它被放在那里,这样应用程序就不会在每次出错时关闭。
标签: c# console-application webclient download