Translate your text using Google Api's

Here is how you can translate a Text using Google's "Unofficial" API's.

The URL for Google Translate is - https://www.google.com/translate\_t?hl=en\&ie=UTF8\&text={0}\&langpair={1}

  • "text" is your input string which needs to be translated.
  • langpair is the language pairs involved in the tranlsation. E.g. "ar|en" means translate from Arabic to English.

The result when you browse to the URL is a HTML page. You will have to do screen scraping to get your translated text.

Below is a C# function which translates, scrapes and gives you the result. I am using String.Substring function but you can use Regex too.

/// <summary>

/// Translate Text using Google Translate API's

/// Google URL - https://www.google.com/translate\_t?hl=en\&ie=UTF8\&text={0}\&langpair={1}

/// </summary>

/// <param name="input">Input string</param>

/// <param name="languagePair">2 letter Language Pair, delimited by "|".

/// E.g. "ar|en" language pair means to translate from Arabic to English</param>

/// <returns>Translated to String</returns>

public string TranslateText(

    string input,

    string languagePair)

{

    string url = String.Format("https://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);

    WebClient webClient = new WebClient();

    webClient.Encoding = System.Text.Encoding.UTF8;

    string result = webClient.DownloadString(url);

    result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);

    result = result.Substring(0, result.IndexOf("</div"));

    return result;

}

More details about this Unofficial Google Translation API can be found Here