none
How to read og:title? RRS feed

  • Question

  • Hi,

    Using below code I am able ot read website Title but I want to know how can I read og:title because most of social media read the og:title and ig not available then I will read the title

    How can I grab the og:title?

    I tried below code but not getting it. Although the highlighted line works perfectly for Title like this:

    readonly Regex regex = new Regex(@"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase);

    Here is the code:

    private async void Button2_Clicked(object sender, EventArgs e)
    {
        // Temp Counter to be Removed;
        string website = EntryURL.Text;
        var st = Stopwatch.StartNew();
        string title = await GetTitle(website);
        st.Stop();
    
        LabelWebsiteTitle.Text = title + $"elapsed: {st.ElapsedMilliseconds}ms";
    }
    
    readonly Regex regex = new Regex(@"\<og:title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</og:title\>", RegexOptions.IgnoreCase);
    
    async Task<string> GetTitle(string website)
    {
        using (var hc = new HttpClient())
        {
            var response = await hc.GetAsync(new Uri(website, UriKind.Absolute))
                .ConfigureAwait(false);
            string source = await response.Content.ReadAsStringAsync()
                .ConfigureAwait(false);
            return regex.Match(source)
                .Groups["Title"]
                .Value;
        }
    }
    


    Thanks,

    Jassim

    Sunday, February 16, 2020 8:15 PM

All replies

  • Hi Jassim Rahma,

    Thank you for posting here.

    According to your description, I hope the following reference could be helpful:

    Read the tag content of Open Graph from code behind

    Besides, it is not reliable to parse HTML with regular expressions.

    Check the suggestions in the following reference:

    What is the best way to parse html in C#?

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, February 17, 2020 2:37 AM
    Moderator