Google Language Translator in C#

In this article I am trying to explain the concept of how to use Google Language Translator in C#? Here I am use Asynchronous Google Translator and create the WebClient instance.

Getting started: -

1.       Create a console application and give the appropriate name.

2.       Create a class for mapping the Language

public static void LanguageMap(Dictionary<string, string> language)

{
       language.Add("Afrikaans", "af");
       language.Add("Albanian", "sq");
       language.Add("Arabic", "ar");
       language.Add("Armenian", "hy");
       language.Add("Azerbaijani", "az");
       language.Add("Basque", "eu");
       language.Add("Belarusian", "be");
       language.Add("Bengali", "bn");
       language.Add("Bulgarian", "bg");
       language.Add("Catalan", "ca");
       language.Add("Chinese", "zh-CN");
       language.Add("Croatian", "hr");
       language.Add("Czech", "cs");
       language.Add("Danish", "da");
       language.Add("Dutch", "nl");
       language.Add("English", "en");
 }

Get all Languages then follow this link http://msdn.microsoft.com/en-us/goglobal/bb896001.aspx

3.       In the Main method write the below line of code.

static void Main(string[] args)

{
    try
    {
        string fromLanguage, toLanguage, text; // create string type of variable
        text = "hello"; // give the text for converting other language
        fromLanguage = "English"; // form language means source language
        toLanguage = "Danish"; // to language for converting in this language
        var language = new Dictionary<string, string>(); // create a Dictionary type variable
        Language.LanguageMap(language); // Call the LanuageMap method for initiate the language.
        Console.WriteLine("Your Text: " + text); // show your raw text on the screen
        Uri address = new Uri("http://translate.google.com/translate_t"); // create a uri type address named variable and uriString means pass the URL.
        WebClient webClient = new WebClient();// create the WebClient instance
        webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; // Give the Content type for WebClents Headers
        webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted); // overload the UploadStringComplete event.
        webClient.UploadStringAsync(address, GetPostData(language[fromLanguage], language[toLanguage], text)); // this method is uploads the specified string to the specified resorce.
        Console.ReadKey();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
        Console.ReadKey();
    }
}

Note: - The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

4.       Create a method with GetPostData() name which is take three parameters with fromLanguage, toLanguage and text and it will put the language translation for from and to and also encode the content.

static string GetPostData(string fromLanguage, string toLanguage, string text)

{
     string data = string.Format("hl=en&ie=UTF8&oe=UTF8submit=Translate&langpair={0}|{1}", fromLanguage, toLanguage); // Here put the language translation for from and to.
     return data += "&text=" + HttpUtility.UrlEncode(text); // Here Encoded the content.
}

 5.       In the last handle the UploadStringComplete event with a method which name is webClient_UploadStringCompleted

static void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)

{
  if (e.Result != null) // Check the event result is null or not.
  {
    var document =new HtmlDocument();// create new HtmlDocument to store my page html.
    document.LoadHtml(e.Result); // Now load the getting Html
    var node = document.DocumentNode.SelectSingleNode("//span[@id='result_box']"); // Here finding particular tag to get value from HtmlDocument
    var output = node != null ? node.InnerText : e.Error.Message;
    Console.WriteLine("Translated Text: " + output); // show the output
  }
}
Full Code: -
using System;

using System.Collections.Generic;
using System.Net;
using System.Web;
using HtmlAgilityPack;

namespace GoogleTranslatorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string fromLanguage, toLanguage, text;
                text = "hello";
                fromLanguage = "English";
                toLanguage = "Danish";
                var language = new Dictionary<string, string>();
                Language.LanguageMap(language);
                Console.WriteLine("Your Text: " + text);
                Uri address = new Uri("http://translate.google.com/translate_t");
                WebClient webClient = new WebClient();
                webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
                webClient.UploadStringAsync(address, GetPostData(language[fromLanguage], language[toLanguage], text));
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadKey();
            }
        }
        static string GetPostData(string fromLanguage, string toLanguage, string text)
        {
            string data = string.Format("hl=en&ie=UTF8&oe=UTF8submit=Translate&langpair={0}|{1}", fromLanguage, toLanguage);
            return data += "&text=" + HttpUtility.UrlEncode(text);
        }
        static void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                var document = new HtmlDocument(); // Here creating new html document to store my page html
                document.LoadHtml(e.Result); // now load getting html
                var node = document.DocumentNode.SelectSingleNode("//span[@id='result_box']"); // finding particular tag to get value from html document
                var output = node != null ? node.InnerText : e.Error.Message;
                Console.WriteLine("Translated Text: " + output); // show the output
            }
        }
    }
    public class Language
    {
        public static void LanguageMap(Dictionary<string, string> language)
        {
            language.Add("Afrikaans", "af");
            language.Add("Albanian", "sq");
            language.Add("Arabic", "ar");
            language.Add("Armenian", "hy");
            language.Add("Azerbaijani", "az");
            language.Add("Basque", "eu");
            language.Add("Belarusian", "be");
            language.Add("Bengali", "bn");
            language.Add("Bulgarian", "bg");
            language.Add("Catalan", "ca");
            language.Add("Chinese", "zh-CN");
            language.Add("Croatian", "hr");
            language.Add("Czech", "cs");
            language.Add("Danish", "da");
            language.Add("Dutch", "nl");
            language.Add("English", "en");
        }
    }
}
Output: -

Google Language Translator in C#

  Modified On Nov-30-2017 06:28:06 AM
  1. Dude, 

    I posted the same article back in Aug 2013. OK as of now the program doesn't work!

    http://www.codeproject.com/Tips/644753/Language-Translator-Using-Google-Translate

Leave Comment