It's quite easy to utilize Google Translate API as shown in the code below
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http; // add NuGet package
using Newtonsoft.Json; // add NuGet package
public class Program
{
public static void Main()
{
// translate "hello world" from english to french
Console.WriteLine(TranslateText("hello world", "en", "fr"));
}
public static string TranslateText(string input, string langCdOriginal, string langCdTranslation)
{
string url = String.Format
("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
langCdOriginal, langCdTranslation, Uri.EscapeUriString(input));
HttpClient httpClient = new HttpClient();
string result = httpClient.GetStringAsync(url).Result;
// Get all json data
var jsonData = JsonConvert.DeserializeObject<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;
}
}
Unfortunately by using the free Google Translate API you will only be allowed to translate a certain ammount of words per hour. After this, Google API will return a 429 (too many requests) error.