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);
           }
       }
   }
}

因此,您可以看到目前我正在迭代和创建文件夹结构,然后我异步下载文件,然后检查文件的文件大小是否小于 1 字节,如果是则将其删除。

我认为我这样做的方式非常繁琐,速度不是很快,而且它使很多文件只删除一次不符合要求的文件。

有没有更快的方法来确定该文件是否存在于 Web 服务器上,并基于该下载是否存在,以及我创建文件夹结构的方式,这是我如何完成我想要的适当的方式吗?

4

1 回答 1

1

有没有更快的方法来确定文件是否存在于网络服务器上

您可以向网络服务器发送 HEAD 请求。

如果网络服务器支持该方法,请检查返回的状态码。

  • 当状态码为 200 时,表示文件确实存在。
  • 当状态码为 404 时,表示该文件不存在。

另一方面,如果网络服务器不支持此方法,您将回退到您的原始代码。

有关详细信息,请参阅此 SO 问题:如何在 C# 中使用 WebClient 发送 HEAD 请求?

我创建文件夹结构的方式,这是一种合适的方式吗

//File zfor循环中有一个不变量:

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");

           // ...
       }
   }
}
于 2016-04-20T09:26:37.610 回答