代码是之前网上找到的,地址为:http://www.crifan.com/teach_you_how_to_find_free_google_translate_api/
原先的代码有不足,如果翻译里包含两个句子,google会返回多句,代码只能获得第一句的翻译,所以这里做了一定的修改。
因为这个api是利用google自己网站的api,说不定哪天更新了就不能用了,所以要用趁早。
static public string TranslateGoogleString(string strToTranslate, string fromLanguage, string toLanguage) { string translatedStr = ""; string transRetHtml = ""; string encodedStr = HttpUtility.UrlEncode(strToTranslate); string googleTransBaseUrl = "http://translate.google.cn/translate_a/t?"; string googleTransUrl = googleTransBaseUrl; googleTransUrl += "&client=" + "t"; googleTransUrl += "&text=" + encodedStr; googleTransUrl += "&hl=" + "zh-CN"; googleTransUrl += "&sl=" + fromLanguage;// source language googleTransUrl += "&tl=" + toLanguage; // to language googleTransUrl += "&ie=" + "UTF-8"; // input encode googleTransUrl += "&oe=" + "UTF-8"; // output encode try { var bytes = new WebClient().DownloadData(googleTransUrl); transRetHtml = Encoding.UTF8.GetString(bytes); var index = transRetHtml.IndexOf("]],"); transRetHtml = transRetHtml.Substring(0, index+1).Replace("[[", ""); foreach (Match m in new Regex(@"[""(.+?)"","".+?"","".+?"",""w*""]").Matches(transRetHtml)) { var s = m.Value.TrimEnd(']') + ","; var g2 = new Regex(@"""(.+?)"",").Match(s).Groups; if (g2.Count >= 2) { translatedStr += g2[1].Value; } } } catch(Exception ex) { Console.WriteLine(ex); } return translatedStr; }