Spread the love
In this tutorial we are going to see how to use the Translator Text API to translate Text from English to Portuguese.
Prerequisites
- To run the sample code you must have an edition of Visual Studio installed.
- You will need the Json.NET NuGet package.
- You will need the .NET SDK installed in your machine
- You will need an Azure Cognitive Services account with a Translator Text resource. If you don’t have an account, you can use the free trial to get a subscription key.
Create your Project
To create an application to translate your text follow the steps below:
- Create a .NET Core Console Application in Visual Studio 2017
- Add the JSON.net nuget package
Install-Package Newtonsoft.Json
- Add the following code under Program
static void Translate() { string SourceLanguage = "en"; string DestinationLanguage = "pt"; string host = "https://api.cognitive.microsofttranslator.com"; string route = "/translate?api-version=3.0&to="+ SourceLanguage + "&to="+ DestinationLanguage; string subscriptionKey = "enter your subscription key"; System.Object[] body = new System.Object[] { new { Text = @"Hello this is a CodeStories post." } }; var requestBody = JsonConvert.SerializeObject(body); using (var client = new HttpClient()) using (var request = new HttpRequestMessage()) { request.Method = HttpMethod.Post; request.RequestUri = new Uri(host + route); request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey); var response = client.SendAsync(request).Result; var jsonResponse = response.Content.ReadAsStringAsync().Result; Console.WriteLine(jsonResponse); Console.WriteLine("Press any key to continue."); } } static void Main(string[] args) { Translate(); Console.ReadLine(); }
- Replace the parameters Source Language and Destination Language. To get supported languages use the Get Languages API. See the tutorial here.
- Replace your subscription key here: string subscriptionKey = “enter your subscription key”;
- Add here the text you want to be translated System.Object[] body = new System.Object[] { new { Text = @”Hello this is a CodeStories post.” } };
- Run the Program
Get Results
The result is in the following format. That’s it we have translated the english text to portuguese.
[{"detectedLanguage":{"language":"en","score":1.0},"translations":[{"text":"Hello this is a CodeStories post.","to":"en"},{"text":"Olá este é um post CodeStories.","to":"pt"}]}]
You can find the complete source code in my Github in this repository in the TextTranslate Project.