For example, there are 2 links:

https://new.vk.com/images/icons/head_icons.png (ссылка на изображение) https://vk.com/images/icons/head_icons.png (битая ссылка, 404-ая страница) 

In the program you need to upload 30,000 images, some links will be broken. How to make a check for the presence of the image link? You can, of course, load the first time as a page and check for any html tag (for example, <html> ), and if there is no this tag, download the second time as an image, but this crutch will not help with such large volumes for you have to load the same thing twice, in most cases.

  • one
    And what, HTTP responses to check is not destiny? Well, there, the Status fields, Content-Type ... (by the way, what does it mean to "download as an image"?) - PinkTux
  • using (WebClient client = new WebClient()) { client.DownloadFile(*ссылка*, *путь*); } using (WebClient client = new WebClient()) { client.DownloadFile(*ссылка*, *путь*); } - Jagailo

1 answer 1

For example, you can:

 static async Task<byte[]> GetContentOrNull(Uri uri) { using (var client = new HttpClient()) using (var response = await client.GetAsync(uri)) { if (!response.IsSuccessStatusCode) // если вернулся плохой статус return null; // возвращаем null using (var content = response.Content) // иначе читаем контент return await content.ReadAsByteArrayAsync(); } } 

You can check the responce.HttpStatusCode code responce.HttpStatusCode more accurately if you want.

If you want to save to a file, use content.CopyToAsync instead of content.ReadAsByteArrayAsync .


To request only the existence of a file, you could use HEAD instead of GET :

 static async Task<bool> CheckContent(Uri uri) { using (var client = new HttpClient()) using (var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, uri))) return response.IsSuccessStatusCode; } 

but for both your links the server returns 501 Not implemented .

  • You can try to request Range - from the first to the second byte. :) - Athari
  • If HEAD is not supported, then surely a partial download too. But yes, it was worth a try :) - VladD