ASP.NET Extension - Translate a String

Using Google translations, translate a string to (almost) any language is a simple solution.
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)

It makes a call to Google API and ask for translation, a WebClient is used and it downloads the string translated.

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;  
 }   

Inga kommentarer:

Skicka en kommentar