Question

I keep trying to translate a textbox content, using the code bellow, it works great on a string with one line, but when it comes to a text paragraph (including line breaks), it just gives me this result: enter image description here this is the code i am using:

string input = textBox1.Text;
        string languagePair = "jp|en";

        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);
        result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
        result = result.Substring(result.IndexOf(">") + 1);
        result = result.Substring(0, result.IndexOf("</span>"));
        result = WebUtility.HtmlDecode(result.Trim());
        MessageBox.Show(result);

Here is a sample of the text: http://pastebin.com/raw.php?i=e9Qcj7B6

Was it helpful?

Solution

I finally got it, i had to modify the code and split it on condition in order to make it work:

string input = textBox1.Text;
string languagePair = "jp|en";

string translation = "";
string[] lines = textBox1.Text.Split('\n');
if (lines.Length > 1)
{
    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 = Encoding.UTF8;
    string result = webClient.DownloadString(url);
    for (int i = 0; i < lines.Length; i++)
    {
        result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
        if (i != lines.Length - 1)
        {
            result = result.Substring(result.IndexOf(">") + 101);
        }
        else
        {
            result = result.Substring(result.IndexOf(">") + 1);
        }
        translation += result.Substring(0, result.IndexOf("</span>"));
    }
    //result = WebUtility.HtmlDecode(result.Trim()); <---- i didn't need this one since i translated from Japanese to English
    MessageBox.Show(translation.Replace("<br>", "\n"));
}
else
{
    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 = Encoding.UTF8;
    string result = webClient.DownloadString(url);
    result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
    result = result.Substring(result.IndexOf(">") + 1);
    result = result.Substring(0, result.IndexOf("</span>"));
    //result = WebUtility.HtmlDecode(result.Trim());
    MessageBox.Show(result.Replace("<br>", "\n"));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top