Search code examples
c#getfiles

Get files from web directory


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!


Solution

  • 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();