using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TranslateText("hi", "German");
}
private void Form1_Load(object sender, EventArgs e)
{
}
public static string TranslateText(string input, string languagePair)
{
return TranslateText(input, languagePair, System.Text.Encoding.UTF7);
}
/// <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, Encoding encoding)
{
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
string result = String.Empty;
using (WebClient webClient = new WebClient())
{
webClient.Encoding = encoding;
result = webClient.DownloadString(url);
}
Match m = Regex.Match(result, "(?<=<div id=result_box dir=\"ltr\">)(.*?)(?=</div>)");
if (m.Success)
result = m.Value;
MessageBox.Show(result);
return result;
}
}
}
I added in the constructor the line:
TranslateText("hi", "German");
And in the bottom i added:
MessageBox.Show(result);
I wanted for the test to translate the word “hi” to German
But the result im getting and in the messagebox is a very long text wich is containing all the google website.
I tried to go manualy to the web site in the string url address and its working im getting to the google translate website.
I dont understand why it dosent work.
I want later to put instead “hi” some text from a text file.
I tried ot use breakpoint and found that this part the Success is all the time return false dont know why:
if (m.Success)
result = m.Value;
I think you are not getting the translated text or value in your html result from your code and also from Google.
Reason:
If you execute this through the browser, it is not translating to the language you expect, example:
http://www.google.com/translate_t?hl=en&ie=UTF8&text=hi&langpair=de
I used
langpair=deorlangpair=Germanand doesn’t work, it shows me always “hi” as my initial text and not “hallo” (text in german).Well, just to answer your question to get the text, do the following:
Add this method to your class:
Change the following in your “TranslateText” method:
Now execute your code like this:
At this point, if you get the translated text from google, it will be retrieved in your app.
Recommendations:
Warning:
Hope this helps 🙂