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:
Install the google cloud SDK: https://dl.google.com/dl/cloudsdk/channels/rapid/GoogleCloudSDKInstaller.exe
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.Shell
gcloud auth application-default login
Install the NuGet package
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'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
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 (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!