Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Google Translate API Usage in C#

0.00/5 (No votes)
4 Oct 2019 2  
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:

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

Example Translate Function

Add the following function to your code:

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):

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:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here