2016-04-18 72 views
1

我正在製作一個簡單的應用程序,它必須從站點獲取子目錄中的所有圖像,並在本地重新創建文件和文件夾結構。以下是我迄今爲止:如何讓此圖片抓取工具更高效?

string folder = "c:\someLocalFolder\"; 

// To keep track of how many files that are processed 
int i = 0; 

// Folder x 
for (int x = 2; x <= 7; x++) 
{ 
    // Folder y 
    for (int y = 0; y < 80; y++) 
    { 
     //File z 
     for (int z = 0; z <= 70; z++) 
     { 
      // File, increment 
      i++; 

      string destFolderPath = Path.Combine(folder, x.ToString(), y.ToString()); 
      string filePath = Path.Combine(destFolderPath, z.ToString() + ".png"); 

      if (!File.Exists(filePath)) 
      { 
       var url = string.Format("http://www.somesite.com/images/{0}/{1}/{2}.png", x, y, z); 
       if (!Directory.Exists(destFolderPath)) 
        // Folder doesnt exist, create 
        Directory.CreateDirectory(destFolderPath); 
       var webClient = new WebClient(); 
       webClient.DownloadFileCompleted += (o, e) => 
       { 
        // less than 1 byte recieved, delete 
        if((new FileInfo(filePath).Length) < 1) 
        { 
         File.Delete(filePath); 
        } 
        // File processed 
        i--; 
        Console.WriteLine(i); 
       }; 
       webClient.DownloadFileAsync(new Uri(url), filePath); 
      } 
      else 
      { 
       // File processed 
       i--; 
       Console.WriteLine(i); 
      } 
     } 
    } 
} 

所以你可以SE目前我迭代和創建文件夾結構,那麼我下載文件異步,然後檢查,如果該文件是文件大小較小大於1個字節如果是的話刪除它。

我覺得我這樣做的方式非常繁瑣,它不是很快,而且它使得很多文件只做一次刪除不符合要求的文件。

有沒有更快速的方式來確定文件是否存在於Web服務器上,並基於該下載如果存在,以及我創建文件夾結構的方式,這是一種合適的方式,我如何做到這一點我想?

回答

1

有沒有確定任何更快的方式,如果該文件的Web服務器上存在

您可以發送HEAD請求到Web服務器。

如果Web服務器支持該方法,請檢查返回的狀態碼。

  • 當狀態碼是200時,表示文件確實存在。
  • 狀態碼爲404時,表示文件不存在。

另一方面,如果web服務器不支持此方法,則回退到您的原始代碼。

詳情請參閱這太問題:How to send a HEAD request with WebClient in C#?

我創建的文件夾結構的方式,這是一種適當的方式

有一個在//File z for循環不變:

string destFolderPath = Path.Combine(folder, x.ToString(), y.ToString()); 

試試這個:

// Folder x 
for (int x = 2; x <= 7; x++) { 
    string xAsString = x.ToString(); 

    // Folder y 
    for (int y = 0; y < 80; y++) { 
     string destFolderPath = Path.Combine(folder, xAsString, y.ToString()); 

     //File z 
     for (int z = 0; z <= 70; z++) { 
      // File, increment 
      i++; 
      string filePath = Path.Combine(destFolderPath, z.ToString() + ".png"); 

      // ... 
     } 
    } 
}