2013-04-24 91 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