2013-04-24 161 views
2

我需要覆蓋的文件位於本地計算機上。我正在檢索的文件來自我的FTP服務器。這些文件都是相同的名稱,但字節不同,例如,它們被更新。WebClient將文件下載到0KB?

我在本地機器上使用文件作爲目標文件 - 這意味着我使用它們的名稱在FTP服務器上輕鬆找到它們。

這是我寫的代碼:代碼完成

private void getFiles() { 

    string startupPath = Application.StartupPath; 
    /* 
    * This finds the files within the users installation folder 
    */ 
    string[] files = Directory.GetFiles(startupPath + "\\App_Data", "*.*", 
    SearchOption.AllDirectories); 

    foreach (string s in files) 
    { 
     /* 
     * This gets the file name 
     */ 
     string fileName = Path.GetFileName(s); 
     /* 
     * This gets the folder and subfolders after the main directory 
     */ 
     string filePath = s.Substring(s.IndexOf("App_Data")); 
     downloadFile("user:[email protected]/updates/App_Data/" + fileName, 
     startupPath + "\\" + filePath); 
    } 
} 

private void downloadFile (string urlAddress, string location) 
{ 
    using (WebClient webClient = new WebClient()) 
    { 
     System.Uri URL = new System.Uri("ftp://" + urlAddress); 
     webClient.DownloadFileAsync(URL, location); 
    } 
} 

後,由於某種原因,在子文件夾中的文件顯示爲0KB。這很奇怪,因爲我知道我的FTP服務器上的每個文件都大於0KB。

我的問題是:爲什麼子文件夾中的文件顯示爲0KB?

如果這篇文章不清楚請告訴我,我會盡我所能來澄清。

+4

不是超級熟悉'WebClient'但不會在下載完成之前就被安置? (因爲您使用的是DownloadFileAsync) – FlyingStreudel 2013-04-24 20:15:15

+0

WebClient用於將文件下載/覆蓋到本地計算機的功能是什麼? – avidprogrammer 2013-04-24 20:25:23

回答

1

在回答評論中的問題時,以下將是一種可能的方式來做到這一點,但不清楚getFiles是否應該是一種阻止方法。在我的例子中,我假設它是(該方法將不會退出,直到所有下載完成)。我不確定這些功能,因爲我從頭開始寫這個功能,但它是一個普遍的想法。

private void getFiles() { 

    string startupPath = Application.StartupPath; 
    /* 
    * This finds the files within the users installation folder 
    */ 
    string[] files = Directory.GetFiles(startupPath + "\\App_Data", "*.*", 
     SearchOption.AllDirectories); 
    using (WebClient client = new WebClient()) 
    { 
     int downloadCount = 0; 
     client.DownloadDataCompleted += 
      new DownloadDataCompletedEventHandler((o, e) => 
      { 
        downloadCount--; 
      }); 
     foreach (string s in files) 
     { 
      /* 
      * This gets the file name 
      */ 
      string fileName = Path.GetFileName(s); 
      /* 
      * This gets the folder and subfolders after the main directory 
      */ 
      string filePath = s.Substring(s.IndexOf("App_Data")); 
      downloadFile(client, "user:[email protected]/updates/App_Data/" + fileName, 
      startupPath + "\\" + filePath); 
      downloadCount++; 
     } 
     while (downloadCount > 0) { } 
    } 
} 

private void downloadFile (WebClient client, string urlAddress, string location) 
{ 
    System.Uri URL = new System.Uri("ftp://" + urlAddress); 
    client.DownloadFileAsync(URL, location); 
} 
+1

我的問題仍然存在:我正在下載的文件顯示爲0KB。 – avidprogrammer 2013-04-24 21:06:41

+0

您可以驗證您是否有權將文件寫入輸出目錄?另外,您可能需要將Accept-Encoding標頭添加到客戶端。 – FlyingStreudel 2013-04-24 21:28:12