How to translate from one language to another using google translator in c#

Following c# code use to translate one language text to another

/// <summary>
    /// Translate
    /// </summary>
    /// <param name="input">translate text </param>
    /// <param name="languagePair"> language codes, Example translate spanish to enligh es|en</param>
    /// <returns></returns>
    public static string Translate(string input, string languagePair)
    {

        string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
        WebClient webClient = new WebClient();
        webClient.Encoding = System.Text.Encoding.UTF8;
        string result = webClient.DownloadString(url);
        Regex regex = new Regex("<span id=result_box.*?>(.*?)<\\/span>");
        var match = regex.Match(result);

        if (match.Success)
        {
            result = match.Value;
            Regex r = new Regex(@"<span[^>].*?>([^<]*)<\/span>", RegexOptions.IgnoreCase);

            foreach (Match matchedSpan in r.Matches(result))
            {
                 result = matchedSpan.Groups[1].Value;
               
            }
        }
    
        return result;     
    }

Comments

Popular posts from this blog

Setup and implement simple angular.js program in MVC

Cross browsers detect print events using javascript

HTML5 drag and drop