[英]How can I make this image crawler more efficient?
我正在制作一個簡單的應用程序,它必須從站點獲取子目錄中的所有圖像並在本地重新創建文件和文件夾結構。 這是我到目前為止所擁有的:
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);
}
}
}
}
因此,正如您目前所看到的,我正在迭代並創建文件夾結構,然后我異步下載文件,然后檢查文件大小是否小於 1 個字節,如果是則將其刪除。
我認為我這樣做很麻煩,速度不是很快,而且它使很多文件只刪除一次不符合要求的文件。
有沒有更快的方法來確定文件是否存在於網絡服務器上,並根據下載是否存在,以及我創建文件夾結構的方式,這是我如何完成我想要的合適的方式?
有沒有更快的方法來確定文件是否存在於 Web 服務器上
您可以向網絡服務器發送 HEAD 請求。
如果網絡服務器支持該方法,請檢查返回的狀態代碼。
另一方面,如果網絡服務器不支持此方法,則回退到原始代碼。
有關詳細信息,請參閱此 SO 問題: 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");
// ...
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.