開始編寫一個簡單的控制檯應用程序,將文件下載到當前位置。出於某種原因,無論文件有多大,我使用的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超出了範圍? –
Web客戶端錯誤發生後,WC.DownloadFileAsync下方的Console.ReadKey()會被觸發。它放在那裏,所以應用程序不會在每次出錯時關閉。 –