Click here to Skip to main content
15,867,895 members
Articles / Programming Languages / C#
Tip/Trick

Google Translate API Usage in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (14 votes)
4 Oct 2019CPOL 38.1K   22   8
How to add translation features to your program. This is not for bulk or commercial usage but for lite usage. For business purposes, use the paid service.

Introduction

We would like to easily translate a string of text to another language. The results returned from the Google Translate API are very cryptic. They are in the form of a JSON jagged array. It is even harder when you have to translate multiple sentences. This tip describes how to properly use the free API using C#.

Requirements

You must add a reference to System.Web.Extensions. Then add the following using directives:

C#
using System.Net.Http;
using System.Collections;
using System.Web.Script.Serialization;

Example Translate Function

Add the following function to your code:

C#
public string TranslateText(string input)
    {
      // Set the language from/to in the url (or pass it into this function)
      string url = String.Format
      ("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
       "en", "es", Uri.EscapeUriString(input));
      HttpClient httpClient = new HttpClient();
      string result = httpClient.GetStringAsync(url).Result;

      // Get all json data
      var jsonData = new JavaScriptSerializer().Deserialize<List<dynamic>>(result);

      // Extract just the first array element (This is the only data we are interested in)
      var translationItems = jsonData[0];

      // Translation Data
      string translation = "";

      // Loop through the collection extracting the translated objects
      foreach (object item in translationItems)
      {
        // Convert the item array to IEnumerable
        IEnumerable translationLineObject = item as IEnumerable;

        // Convert the IEnumerable translationLineObject to a IEnumerator
        IEnumerator translationLineString = translationLineObject.GetEnumerator();

        // Get first object in IEnumerator
        translationLineString.MoveNext();

        // Save its value (translated text)
        translation += string.Format(" {0}", Convert.ToString(translationLineString.Current));
      }

      // Remove first blank character
      if (translation.Length > 1) { translation = translation.Substring(1); };

      // Return translation
      return translation;
    }

Set the from/to language in the following line. In this case, en (from language) and es (to language):

C#
string url = String.Format
("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}", 
"en", "es", Uri.EscapeUriString(input));

Then call your code:

C#
string translatedText = TranslateText(text);

Points of Interest

You will only be allowed to translate about 100 words per hour using the free API. If you abuse this, Google API will return a 429 (Too many requests) error.

History

  • 10/4/2019: Original version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionpurchasing methode Pin
Member 150399233-Jun-21 19:44
Member 150399233-Jun-21 19:44 
haw can i buy a paid api of this
Questionstring result = httpClient.GetStringAsync(url).Result; ( This funcion is not working in visual studio 2012) Pin
Rajendra Koranga15-May-21 3:14
Rajendra Koranga15-May-21 3:14 
QuestionUnlimited translation required Pin
PallavSingh6-Jun-20 11:40
professionalPallavSingh6-Jun-20 11:40 
AnswerRe: Unlimited translation required Pin
Member 150399233-Jun-21 19:44
Member 150399233-Jun-21 19:44 
PraiseGreat Pin
Sammuel Miranda16-Oct-19 8:01
professionalSammuel Miranda16-Oct-19 8:01 
GeneralRe: Great Pin
SeaWater23-Oct-19 9:37
SeaWater23-Oct-19 9:37 
GeneralBad practice Pin
Eric Lapouge4-Oct-19 7:53
Eric Lapouge4-Oct-19 7:53 
GeneralGood Practice Pin
SeaWater23-Oct-19 9:36
SeaWater23-Oct-19 9:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.