Пример #1
0
 /// <summary>
 /// Translate Text using Google Translate
 /// </summary>
 /// <param name="input">The string you want translated</param>
 /// <param name="languagePair">2 letter Language Pair, delimited by "|". 
 /// e.g. "en|da" language pair means to translate from English to Danish</param>
 /// <param name="encoding">The encoding.</param>
 /// <returns>Translated to String</returns>
 public static string TranslateText(string input, string languagePair)
 {
     string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", System.Web.HttpUtility.UrlEncode(input), languagePair);
     WebClient webClient = new WebClient();
     webClient.Encoding = System.Text.Encoding.UTF8;
     string result = webClient.DownloadStringUsingResponseEncoding(url);
     result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
     result = result.Substring(result.IndexOf(">") + 1);
     result = result.Substring(0, result.IndexOf("</span>"));
     return System.Web.HttpUtility.HtmlDecode(result.Trim());
 }
Пример #2
0
        /// <summary>
        /// Translate Text using Google Translate
        /// </summary>
        /// <param name="input">The string you want translated</param>
        /// <param name="languagePair">2 letter Language Pair, delimited by "|". 
        /// e.g. "en|da" language pair means to translate from English to Danish</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>Translated to String</returns>
        public static string TranslateText(string input, string languagePair)
        {
            //string url = String.Format("http://www.google.hr/translate_t?hl=hr&ie=UTF8&text={0}&langpair={1}", Uri.EscapeUriString(input).Replace("#", "%23"), languagePair);
            string url = String.Format("http://translate.google.com/?hl=en&ie=UTF8&text={0}&langpair={1}", Uri.EscapeUriString(input).Replace("#", "%23"), languagePair);

            var webClient = new WebClient { Encoding = Encoding.UTF8 };

            // MUST add a known browser user agent or else response encoding doen't return UTF-8 (WTF Google?)
            webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0");
            webClient.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8");

            string result = webClient.DownloadStringUsingResponseEncoding(url);

            result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
            result = result.Substring(result.IndexOf(">") + 1);
            result = result.Substring(0, result.IndexOf("</span>"));

            return result.Trim();
        }