Introduction
Since everyone wants their application to be presented according to the user's culture, location, etc, in this example I used the Google Translator, calling GoogleTranslator by HttpRequest
and reading the Translated string from the Response stream.
Background
This code will click many ideas in your mind as to how you can use resources already available in the market using HttpRequest
and Response
.
Using the Code
In the below code, I translate from English Language to the required language. You can change it to the desired culture. Just replace 'en' with the desired culture name.
private string Translate(string text, string l)
{
string translated = null;
HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create
("http://translate.google.com/translate_s?hl=en&clss=&q=" +
text.Replace(" ", "+") + "&tq=&sl=en&tl=" + l);
HttpWebResponse res = (HttpWebResponse)hwr.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string html = sr.ReadToEnd();
int rawlength1 = html.IndexOf("<span id=otq><b>");
string rawStr1 = html.Substring(rawlength1);
int rawlength2 = rawStr1.IndexOf("</b>");
string rawstr2 = rawStr1.Substring(0, rawlength2);
translated = rawstr2.Replace("<span id=otq><b>", "");
tbStringToTranslate.Text = text;
return translated;
}
Points of Interest
I have written this code to localize my application texts, Labels...... I too used to store translated stings in my DataBase. This makes me use this code as I don't need to feed translated data in database whenever a required text to translate is passed to it. First look in DB, if not found it gets it from Google Translator and feeds in DB. I don't even require to maintain resource files for different cultures because I get the Current culture from System.Globalization.CultureInfo.CurrentCulture
and pass it to Translate();
History
- 25th January, 2010: Initial post
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.