Home > Uncategorized > Automatically translate RESX Resource files using #Azure Cognitive Translator in C#

Automatically translate RESX Resource files using #Azure Cognitive Translator in C#

You should always have your RESX files manually translated by a professional translator, but if you’re in a hurry and quality is less important than speed, then you can use an automated translator. But be warned, you could be saying silly text on your website.

So, given a source, English text Resx, and an output file, we’ll say in Russian, we can define our main method as follows;

static void Main(string[] args)
{
	var inputFile = @"C:\Users\fiach\Desktop\Strings.en-NZ.resx";
	var outputFile = @"C:\Users\fiach\Desktop\Strings.ru-RU.resx";
	var inputXml = File.ReadAllText(inputFile);
	var xDoc = new XmlDocument();
	xDoc.LoadXml(inputXml);
	var dataNodes = xDoc.SelectNodes("//data");
	foreach (XmlNode dataNode in dataNodes)
	{
		var english = dataNode.SelectSingleNode("value").InnerText;
		Console.WriteLine(english);
		var russian = Translate(english, "en", "ru");
		Console.WriteLine(russian);
		dataNode.SelectSingleNode("value").InnerText = russian;
	}
	File.WriteAllText(outputFile, xDoc.InnerXml);
}

Then, we implement the Translate method as follows;

public static string Translate(string text, string fromLanguage, string toLanguage)
{
	try
	{
		const string strKey = "**************";
		ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |
											   SecurityProtocolType.Tls |
											   SecurityProtocolType.Tls11 |
											   SecurityProtocolType.Tls12;
		var url = string.Format("https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to={0}&from={1}", toLanguage, fromLanguage);
		var wc = new WebClient();
		wc.Headers["Ocp-Apim-Subscription-Key"] = strKey;
		wc.Headers["Ocp-Apim-Subscription-Region"] = "westeurope";
		wc.Encoding = Encoding.UTF8;
		var jPost = new[] { new { Text = text } };
		var post = JsonConvert.SerializeObject(jPost, Newtonsoft.Json.Formatting.Indented);
		wc.Headers[HttpRequestHeader.ContentType] = "application/json";
		var json = "";
		try
		{
			json = wc.UploadString(url, "POST", post);
		}
		catch (WebException exception)
		{
			string strResult = "";
			if (exception.Response != null)
			{
				var responseStream = exception.Response.GetResponseStream();
				if (responseStream != null)
				{
					using (var reader = new StreamReader(responseStream))
					{
						strResult = reader.ReadToEnd();
					}
				}
			}
			throw new Exception(strResult);
		}
		var jResponse = JArray.Parse(json);
		var translation = jResponse.First["translations"].First["text"].ToString();
		return translation;
	}
	catch
	{
		return text;
	}
}

You also need the Newtonsoft.JSON Nuget package for this, and an API key too!

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment