-2

I wanted to just get random Images from http://random.cat/, so I wanted to index them using Directory.GetFiles or something like that, but this doesn't work. So what would be the best way to get the functionality of Directory.GetFiles but for http://random.cat/i (this is where the Images are stored, I think)?

Thanks in advance!

Devid Farinelli
  • 7,514
  • 9
  • 42
  • 73
LordOsslor
  • 13
  • 1
  • 7

3 Answers3

0

You do not have access to the images database but they provide an api to retrieve one image at a time.

Create a basic model:

public class RandomImage
{
    public string file { get; set; }
}

Then you can use WebClient to do that:

public string RandomImage()
{
    string result = null;

    var apiurl = "http://random.cat";

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(apiurl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage ResponseMessage = client.GetAsync(apiurl + "/meow").Result; // The .Result part will make this method not async
    if (ResponseMessage.IsSuccessStatusCode)
    {
        var ResponseData = ResponseMessage.Content.ReadAsStringAsync().Result;
        var MyRandomImage = JsonConvert.DeserializeObject<RandomImage>(ResponseData);

        result = MyRandomImage.file; // This is the url for the file
    }

    // Return
    return result;
}

Call the function from your methods:

var MyImage = RandomImage();
Cristian Szpisjak
  • 2,429
  • 2
  • 19
  • 32
0

Directory.GetFiles() is designed to be used on a filesystem, not on web addresses.

This link ought to be enough to get you started. Since you don't know the actual URL of the picture, you would have to parse the page to find it and then make a further request to download it.

Be aware that they might block you out if you download too many images in a certain time.

EDIT: I noticed just now that they have an API, which makes everything a bit simpler. But it's marked as temporary, so make of that what you will.

Community
  • 1
  • 1
s.m.
  • 7,895
  • 2
  • 38
  • 46
0

As mentioned you have to use HttpClient. I dont know any method for listing all files, but this also needs to be set up in the web server hosting the site.