Custom Google Search Engine in C#

Custom Google Search Engine in C#

Create Custom Google Search Engine

  1. Firstly you need a Google account
  2. Get Google Api
    • Goto https://console.developers.google.com
    • create a project
    • enable custom search api
    • in Project, goto credentials and create a new key and select this a browser key
    • note down the key to be used later
  3. Create Google Search
    • Goto https://www.google.com/cse/all
    • Click on add to add new custom search
    • Under sites, put the sites that you want your search to be limit eg
      • www.universityofdunden.co.nz,   ———-> specifically one url
      • *.co.nz    ———-> all companies in new zealand
    • Under Name of Search –> put a name of your search
    • Click create and you see a “Congratulations”
    • googlesearch03Click ok and goto setup and click on search engine key. Note this down as we will need this later googlesearch4
    • If need to reproduce this google search in your webpage just click on Get Code and paste in your javascript
  4. Coding in Visual Studio
    • Create a new console project
    • Goto Nuget Manager and search for “Google.Apis.Customsearch.v1 Client” to install into your project
    • Enter the code below :- Put your API and SearchEngine from previous step
    • private static void Main(string[] args)
      {
          const string apiKey = "XXXXXXX";
          const string searchEngineId = "XXXXX";
          const string query = "Exampletest";
          CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey });
          Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(query);
          listRequest.Cx = searchEngineId;
          Search search = listRequest.Execute();
          foreach (var item in search.Items)
          {
              Console.WriteLine("Title : " + item.Title + Environment.NewLine + "Link : " + item.Link + Environment.NewLine + Environment.NewLine);
          }
          Console.ReadLine();
      }

       

    • Run this should give the results of Search google query in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *