web scrape my reddit account to grab the latest post in csharp

To get the latest post from a Reddit account in C#, you will need to use the Reddit API and a HTTP client such as HttpClient. Here are the steps:

  1. Get an access token for the Reddit API by following the instructions on https://www.reddit.com/dev/api/.

  2. Use HttpClient to make an HTTP GET request to the Reddit API endpoint that returns the latest post of a user. The endpoint is https://oauth.reddit.com/user/{username}/submitted.json?limit=1.

  3. Deserialize the JSON response into a C# object using a JSON serializer such as Newtonsoft.Json.

  4. Access the properties of the C# object to get the data of the latest post.

Here is some sample code to achieve this:

main.cs
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;

public class RedditPost
{
    public string title { get; set; }
    public string permalink { get; set; }
    public string subreddit { get; set; }
    public string url { get; set; }
}

public static async Task<RedditPost> GetLatestPost(string accessToken, string username)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
    
    var response = await client.GetAsync($"https://oauth.reddit.com/user/{username}/submitted.json?limit=1");
    var json = await response.Content.ReadAsStringAsync();
    
    var data = JsonConvert.DeserializeObject<dynamic>(json);
    var post = data.data.children[0].data;

    return new RedditPost
    {
        title = post.title,
        subreddit = post.subreddit,
        url = post.url,
        permalink = "https://www.reddit.com" + post.permalink
    };
}
982 chars
33 lines

You can call this method with the access token and username of the Reddit account you want to scrape:

main.cs
var accessToken = "your access token";
var username = "your username";

var latestPost = await GetLatestPost(accessToken, username);
Console.WriteLine($"Title: {latestPost.title}");
Console.WriteLine($"Subreddit: {latestPost.subreddit}");
Console.WriteLine($"URL: {latestPost.url}");
Console.WriteLine($"Permalink: {latestPost.permalink}");
341 chars
9 lines

This will print the data of the latest post in the console.

gistlibby LogSnag