サイトからサブディレクトリ内のすべての画像を取得し、ファイルとフォルダー構造をローカルに再作成する必要がある単純なアプリケーションを作成しています。これが私がこれまでに持っているものです:
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サーバーに存在するかどうかを判断するより高速な方法はありますか?また、存在する場合はそのダウンロードに基づいて、フォルダー構造を作成する方法は、私が望むものを達成するための適切な方法ですか?