Google Search in C#: A step by step walk-through tutorial


In previous post, the implementation of Google book search in C# is discussed. In this post, the similar approach is used to implement Google Custom Search in C#.

image

Download the source project at Github here.

The code is very simple:

public static IList<Result> Search(string query)
{
    Console.WriteLine("Executing custom search for query: {0} ...", query);

    CseResource.ListRequest listRequest = Service.Cse.List(query);
    listRequest.Cx = cx;

    Search search = listRequest.Execute();
    return search.Items;
}


To get this code running, we need an instance variable called Service:

//API Key
private static string API_KEY = "AIzaSyCsqAm43dcaVHD6ycUEWTbCNtg4rD_aa8Y";

//The custom search engine identifier
private static string cx = "015598178761323117960:sbbkk2__0lo";

public static CustomsearchService Service = new CustomsearchService(
    new BaseClientService.Initializer
{
    ApplicationName = "ISBNBookCsutomSearch",
    ApiKey = API_KEY,
});

To get this code compile, you need to add reference to the Google Custom Search Library:

  • You can use Nuget command: Install-Package Google.Apis.Customsearch.v1  or
  • Right click on project reference >  Manage Nuget Packages > Search “Google.Apis.Customsearch.v1” in the top right corner > Install the found package

image

Compile and Run the below test code:

class Program
{
    static void Main(string[] args)
    {
        string query = "The University of Hong Kong";
        var results = GoogleSearch.Search(query);
        foreach (Result result in results)
        {
            Console.WriteLine("-----------------------------------");
            Console.WriteLine("Title: {0}", result.Title);
            Console.WriteLine("Link: {0}", result.Link);
        }
        Console.ReadKey();
    }
}

You should have a success in running Google search of your custom keyword!

Again, you might wonder what are the API KEY and cx? How to get these two strings?

  • Goto Google Developer Console
  • Create a project
  • Click “Credentials” on the left Tab
  • Click “Create new key” button on the right panel

image image

image image

  • You are then offered an API KEY:

    image

  • To get the Custom Search engine ID (cx), follow below procedures:

  • One last step: turn on the custom search api in your development console:

image

As you can see, the code is trivial, and the complexity is mostly due to Google configurations!

Happy coding and the code project can be found at Github here.

8 thoughts on “Google Search in C#: A step by step walk-through tutorial

  1. Sven

    Hi there,
    thanks for the splendid tutorial and the example code, it helped me a lot.
    Now I run a search following your example and when I compare the number of results I get via the API to the number of results I get via the Google website, the API returns significantly less results.
    Do you have any idea how that could come?

  2. xinyustudio

    The custom search is different from your google search via web, it is normal. If you want exactly the same results as you do in browser, you can use HttpAgility Pack to query at runtime!

  3. Tom

    Hi! Thanks for the tutorial 🙂

    Just a question, how can I order more results for given query? Is there any chance to print all the results till the “no more results” flag?

    Cheers,
    Tom

  4. xinyustudio

    var results = GoogleSearch.Search(query); this returns IEnumerable, you can use LINQ to sort the results by any order. e.g. var results2 = results.Where (item => item.SomeProperty == “abc”);

  5. blake

    Hi! I tried your code and modify it a little as I am using MVC.

    List search_list = new List();
    foreach (var item in search.Items)
    {
    var list = new SearchList();
    list.AdLink = item.Link;
    list.AdTitle = item.Title;
    list.AdDetails = item.Snippet;
    list.AdOptions = item.Labels;
    search_list.Add(list);
    }

    But then in my view page, it says that my search_list is NullReferenceException.

    @if (Model.search_list.Count != 0)
    {

    @foreach (var item in Model.search_list)
    {
    @item.AdLink
    @item.AdTitle
    @item.AdDetails
    }

    }

    Please help me.

  6. Pingback: Bing Search in C#: A step by step walk-through tutorial | Xinyustudio

Leave a comment