Following our previous post about Azure AI Translator, this post will show how to translate text between a source and target language using C#.
About Azure AI Translator
Microsoft Azure AI Translator offers translation services like language detection and translation for over 90 languages using a single API endpoint.
The process to use Azure AI Translator starts with the provisioning of an Azure AI Service (Multi-service or Translator) and using an SDK or Azure REST API to use the service.
Azure AI Translator offers two core services: Language detection and Language translations. To use the detection service, we need to send a text in a key-value pair format with the language that we would like to detect.
The translation service uses two parameters, From and To, that indicate the source (From) and target (To) languages. We can also count the number of characters in a translated sentence using built-in functions that come with the API.
How to Translate Text Using Azure AI Translator and .NET
The following C# program uses the Azure AI Translator REST API endpoint to translate text (Source to Target). To get started, create a C# project and install the Translation library.
dotnet add package Azure.AI.Translation.Text --version 1.0.0-beta.1
In your .NET project, create a appsettings.json
file with the details of your access key and region.
{
"TranslatorKey": "ACCESS KEY",
"TranslatorRegion": "AZURE REGION"
}
In your Programs.cs
file, add the following code.
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;
using Azure;
using Azure.AI.Translation.Text;
namespace translate_text
{
/// <summary>
/// Main program class for text translation.
/// </summary>
class Program
{
/// <summary>
/// Main entry point for the application.
/// </summary>
/// <param name="args">Command-line arguments.</param>
static async Task Main(string[] args)
{
try
{
// Set console encoding to Unicode
Console.InputEncoding = Encoding.Unicode;
Console.OutputEncoding = Encoding.Unicode;
// Load configuration from appsettings.json
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
string translatorRegion = configuration["TranslatorRegion"];
string translatorKey = configuration["TranslatorKey"];
// Create translation client
AzureKeyCredential credential = new(translatorKey);
TextTranslationClient client = new(credential, translatorRegion);
// Fetch supported languages
var languagesResponse = await client.GetLanguagesAsync(scope: "translation");
var languages = languagesResponse.Value;
Console.WriteLine($"{languages.Translation.Count} languages available.");
Console.WriteLine("Enter a target language code for translation (e.g., 'EN'):");
// Prompt user for target language code
string targetLanguage;
while (true)
{
targetLanguage = Console.ReadLine();
if (languages.Translation.ContainsKey(targetLanguage))
break;
Console.WriteLine($"{targetLanguage} is not a supported language.");
}
// Continuously prompt user for text to translate
string inputText;
while (true)
{
Console.WriteLine("Enter text to translate ('quit' to exit):");
inputText = Console.ReadLine();
if (inputText.ToLower() == "quit")
break;
// Translate the entered text
var translationResponse = await client.TranslateAsync(targetLanguage, inputText);
var translation = translationResponse.Value[0];
string sourceLanguage = translation?.DetectedLanguage?.Language;
Console.WriteLine($"'{inputText}' translated from {sourceLanguage.ToUpper()} to {translation?.Translations[0].To.ToUpper()} as '{translation?.Translations[0]?.Text}'.");
}
}
catch (Exception ex)
{
// Handle exceptions
Console.WriteLine(ex.Message);
}
}
}
}