ASP.NET 3.5 Extension - Translate a String
Using Google translations, translate a string to (almost) any language.
Since it is an extension, it will be available like myString.Translate("sv","en"); but you can of course use it as a regular method by removing the arg 'this string s'.
Note that the web server must be able to make web requests to google.com.
You can use both codes like "en" or the culture and lang "sv-SE" version (takes the first one)
C# code:
using System;
using System.Text;
using System.Net;
public static string Translate(this string s, string langFrom, string langTo)
{
if (String.IsNullOrEmpty(s))
return String.Empty;
if (langFrom.Contains("-"))
langFrom = langFrom.Split('-')[0];
if (langTo.Contains("-"))
langTo = langTo.Split('-')[0];
string address = string.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}%7C{2}", s, langFrom, langTo);
string html = new WebClient().DownloadString(address);
string block = html.Substring(html.IndexOf("id=result_box") + 0x18, 500);
string phrase = block.Substring(0, block.IndexOf("</div"));
return phrase;
}
Comments