Using the Google Translate API in .NET or .NET Core

In the company I work, we use the Google Translate API to translate the documentation of our products from English to French and Spanish. To be honest, the translations are very very amazing! This doesn't mean you won't have to rephrase some sentences, but the quality of the translations are pretty amazing!

The Google Translate service is easy to use:

  1. Install the google cloud sdk: https://dl.google.com/dl/cloudsdk/channels/rapid/GoogleCloudSDKInstaller.exe
  2. Run the following command line to authenticate the Google services. Your code will use this account automatically when you don't set creds in your code. This is very convenient while developping your application.
 gcloud auth application-default login
  1. Install the NuGet package Google.Cloud.Translation.V2 (.NETStandard 1.3)
  2. Use the TranslationClient
var message = "This is some html text to <strong>translate</strong>!";
string targetLanguage = "fr";
string sourceLanguage = null; // automatically detected
var client = Google.Cloud.Translation.V2.TranslationClient.Create();
var response = client.TranslateHtml(message, targetLanguage, sourceLanguage);
Console.WriteLine(response.TranslatedText);
// C&#39;est un texte html à <strong>traduire</strong> !

Google Translate automatically detects the source language, so you don't need to specify it. In our documents there are some words we don't want to translate, such as function names, or business concepts. To prevent Google Translate from translating theses words, you can enclosed the text with a span having the class notranslate:

<span class="notranslate">text</span>

You'll find more options to control the translation in the documentation: https://cloud.google.com/translate/docs/

Last but not least, the service cost about $20 per million characters (princing). To my mind, it's not very expensive for the quality of the translations and the time we saved.

Follow me:
Enjoy this blog? Buy Me A Coffee Donate with PayPal

Leave a reply