2013-01-17 41 views
-1

我會嘗試使用此代碼下載文件。但文件大小爲0 KB。什麼是正確和有效的方式來下載文件。使用Windows窗體應用程序下載任何文件與c#

private void DownloadFile() 
{ 
    using (WebClient Client = new WebClient()) 
    { 
     Client.DownloadFileAsync(
      new Uri("http://localhost/sn/userSelect.Designer.cs", UriKind.Absolute), 
      @"C:\xampp\htdocs\sn\test1.txt"); 
     Client.Dispose(); 
    } 
} 

任何一個可以給我的方法下載了Windows窗體程序的文件在C#.thanks

+2

你看了(HTTP的['爲文檔DownloadFileAsync']:// MSDN。 microsoft.com/en-us/library/ms144196.aspx)? –

+3

特別是,您認爲「異步」部分意味着什麼? –

+0

我將使用兩種方法,例如** DownloadFileAsync **和** DownloadFile **,但結果相同。 :( – Elshan

回答

1
class Program 
{ 
    private static WebClient wc = new WebClient(); 
    private static ManualResetEvent handle = new ManualResetEvent(true); 
    private static void Main(string[] args) 
    { 

     wc.DownloadProgressChanged += WcOnDownloadProgressChanged; 
     wc.DownloadFileCompleted += WcOnDownloadFileCompleted; 
     wc.DownloadFileAsync(new Uri(@"http://www.nattyware.com/bin/pixie.exe"), @"C:\\pixie.exe"); 
     handle.WaitOne(); // wait for the async event to complete 

    } 

    private static void WcOnDownloadFileCompleted(object sender, AsyncCompletedEventArgs e) 
    { 
     if (!e.Cancelled && e.Error == null) 
     { 
      //async download completed successfully 
     } 
     handle.Set(); // in both the case let the void main() know that async event had finished so that i can quit 
    } 

    private static void WcOnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
    { 
     // handle the progres in case of async 
     //e.ProgressPercentage 
    } 
相關問題