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

  • Gérald Barré

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:

  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 developing your application.

    gcloud auth application-default login
  3. Install the NuGet package Google.Cloud.Translation.V2 (.NETStandard 1.3)

  4. 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);
    // 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 these words, you can enclose 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:

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

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub