How to translate text with Babelfish

14 views Asked by At

I am looking for a quick and easy way to translate strings. I decided (but that is not compulsory) to go for BabelFish.

public class BabelfishTranslator
{
    public string Translate(string resource, System.Globalization.CultureInfo from, System.Globalization.CultureInfo to)
    {
        string[] VALIDTRANSLATIONMODES = new string[]
        {
            "en_zh", "en_fr", "en_de", "en_it", "en_ja", "en_ko",
            "en_pt", "en_es", "zh_en", "fr_en", "fr_de", "de_en",
            "de_fr", "it_en", "ja_en", "ko_en", "pt_en", "ru_en", "es_en"
        };

        Uri uri = new Uri("http://www.babelfish.com");
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

        string postsourcedata;
        string translationmode = "en_it"; // Example: English to Italian
        postsourcedata = "lp=" + translationmode + "&tt=urltext&intl=1&doit=done&urltext=" + HttpUtility.UrlEncode(resource);

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postsourcedata.Length;
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";

        using (Stream writeStream = request.GetRequestStream())
        {
            byte[] bytes = Encoding.UTF8.GetBytes(postsourcedata);
            writeStream.Write(bytes, 0, bytes.Length);
        }

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream responseStream = response.GetResponseStream())
        using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
        {
            string page = readStream.ReadToEnd();
            Regex reg = new Regex(@"<div style=padding:10px; lang=..> (.*?)</div>");
            MatchCollection matches = reg.Matches(page);

            if (matches.Count != 1 || matches[0].Groups.Count != 2)
            {
                return "error";
            }

            return matches[0].Groups[1].Value;
        }
    }
}

and then I use it with:

var translator = new BabelfishTranslator();
var translatedText = translator.Translate("Hello, world!", new System.Globalization.CultureInfo("en"), new System.Globalization.CultureInfo("it"));
Console.WriteLine($"Translated text: {translatedText}");

but what I get is just error for it is getting 0 responses so in short it doesn't work.

Thanks

0

There are 0 answers