我正在制作一个简单的应用程序,它必须从站点获取子目录中的所有图像并在本地重新创建文件和文件夹结构。这是我到目前为止所拥有的:
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 服务器上,并基于该下载是否存在,以及我创建文件夹结构的方式,这是我如何完成我想要的适当的方式吗?