========================================================================
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
From my experience. I think you can use HttpWebRequest for requesting that page and passing parameters.
Please double check that code. that will works fine in the .NET version 2.0, 3.0, 3.5.
/// <summary>
/// Translate Text using Google Translate API's
/// Google URL - http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}
/// </summary>
/// <param name="input">Input string</param>
/// <param name="languagePair">2 letter Language Pair, delimited by "|".
/// E.g. "ar|en" language pair means to translate from Arabic to English</param>
/// <returns>Translated to String</returns>
public string TranslateText(
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);
result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
result = result.Substring(0, result.IndexOf("</div"));
return result;
}
Let me know whether that answers your question, or if I've missed something.
Please mark the replies as answers if they help or unmark if not.
If you have any feedback about my replies, please contact msdnmg@microsoft.com
the problem with the above code doesnot return translated text it is actually returning a blank text. thanks for your help. i have found a new way to do this. here is the code
public static class Language
{
public const string AFRIKAANS = "af";
public const string ALBANIAN = "sq";
public const string AMHARIC = "am";
public const string ARABIC = "ar";
public const string ARMENIAN = "hy";
public const string AZERBAIJANI = "az";
public const string BASQUE = "eu";
public const string BELARUSIAN = "be";
public const string BENGALI = "bn";
public const string BIHARI = "bh";
public const string BULGARIAN = "bg";
public const string BURMESE = "my";
public const string CATALAN = "ca";
public const string CHEROKEE = "chr";
public const string CHINESE = "zh";
public const string CHINESE_SIMPLIFIED = "zh-CN";
public const string CHINESE_TRADITIONAL = "zh-TW";
public const string CROATIAN = "hr";
public const string CZECH = "cs";
public const string DANISH = "da";
public const string DHIVEHI = "dv";
public const string DUTCH = "nl";
public const string ENGLISH = "en";
public const string ESPERANTO = "eo";
public const string ESTONIAN = "et";
public const string FILIPINO = "tl";
public const string FINNISH = "fi";
public const string FRENCH = "fr";
public const string GALICIAN = "gl";
public const string GEORGIAN = "ka";
public const string GERMAN = "de";
public const string GREEK = "el";
public const string GUARANI = "gn";
public const string GUJARATI = "gu";
public const string HEBREW = "iw";
public const string HINDI = "hi";
public const string HUNGARIAN = "hu";
public const string ICELANDIC = "is";
public const string INDONESIAN = "id";
public const string INUKTITUT = "iu";
public const string ITALIAN = "it";
public const string JAPANESE = "ja";
public const string KANNADA = "kn";
public const string KAZAKH = "kk";
public const string KHMER = "km";
public const string KOREAN = "ko";
public const string KURDISH = "ku";
public const string KYRGYZ = "ky";
public const string LAOTHIAN = "lo";
public const string LATVIAN = "lv";
public const string LITHUANIAN = "lt";
public const string MACEDONIAN = "mk";
public const string MALAY = "ms";
public const string MALAYALAM = "ml";
public const string MALTESE = "mt";
public const string MARATHI = "mr";
public const string MONGOLIAN = "mn";
public const string NEPALI = "ne";
public const string NORWEGIAN = "no";
public const string ORIYA = "or";
public const string PASHTO = "ps";
public const string PERSIAN = "fa";
public const string POLISH = "pl";
public const string PORTUGUESE = "pt-PT";
public const string PUNJABI = "pa";
public const string ROMANIAN = "ro";
public const string RUSSIAN = "ru";
public const string SANSKRIT = "sa";
public const string SERBIAN = "sr";
public const string SINDHI = "sd";
public const string SINHALESE = "si";
public const string SLOVAK = "sk";
public const string SLOVENIAN = "sl";
public const string SPANISH = "es";
public const string SWAHILI = "sw";
public const string SWEDISH = "sv";
public const string TAJIK = "tg";
public const string TAMIL = "ta";
public const string TAGALOG = "tl";
public const string TELUGU = "te";
public const string THAI = "th";
public const string TIBETAN = "bo";
public const string TURKISH = "tr";
public const string UKRAINIAN = "uk";
public const string URDU = "ur";
public const string UZBEK = "uz";
public const string UIGHUR = "ug";
public const string VIETNAMESE = "vi";
public const string UNKNOWN = "";
public static string Translate(string stringToTranslate, string fromLanguage, string toLanguage)
{
// make sure that the passed string is not empty or null
if (!String.IsNullOrEmpty(stringToTranslate))
{
// per Google's terms of use, we can only translate
// a string of up to 5000 characters long
if (stringToTranslate.Length <= 5000)
{
const int bufSizeMax = 65536;
const int bufSizeMin = 8192;
try
{
// by default format? is text.
// so we don't need to send a format? key
string requestUri = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + stringToTranslate + "&langpair=" + fromLanguage + "%7C" + toLanguage;
// execute the request and get the response stream
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
// get the length of the content returned by the request
int length = (int)response.ContentLength;
int bufSize = bufSizeMin;
// allocate buffer and StringBuilder for reading response
byte[] buf = new byte[bufSize];
StringBuilder sb = new StringBuilder(bufSize);
// read the whole response
while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
{
sb.Append(Encoding.UTF8.GetString(buf, 0, length));
}
// the format of the response is like this
// {"responseData": {"translatedText":"¿Cómo estás?"}, "responseDetails": null, "responseStatus": 200}
// so now let's clean up the response by manipulating the string
string translatedText = sb.Remove(0, 36).ToString();
translatedText = translatedText.Substring(0,
translatedText.IndexOf("\"},"));
return translatedText;
}
catch
{
return "Cannot get the translation. Please try again later.";
}
}
else
{
return "String to translate must be less than 5000 characters long.";
}
}
else
{
return "String to translate is empty.";
}
}
}
Marked as answer by shaheen256 on Nov 06, 2009 03:55 AM
I am also working on the same.I got the code similar to u.This is my code:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Net;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
public class Language
{
public const string AFRIKAANS = "af";
public const string ALBANIAN = "sq";
public const string AMHARIC = "am";
public const string ARABIC = "ar";
public const string ARMENIAN = "hy";
public const string AZERBAIJANI = "az";
public const string BASQUE = "eu";
public const string BELARUSIAN = "be";
public const string BENGALI = "bn";
public const string BIHARI = "bh";
public const string BULGARIAN = "bg";
public const string BURMESE = "my";
public const string CATALAN = "ca";
public const string CHEROKEE = "chr";
public const string CHINESE = "zh";
public const string CHINESE_SIMPLIFIED = "zh-CN";
public const string CHINESE_TRADITIONAL = "zh-TW";
public const string CROATIAN = "hr";
public const string CZECH = "cs";
public const string DANISH = "da";
public const string DHIVEHI = "dv";
public const string DUTCH = "nl";
public const string ENGLISH = "en";
public const string ESPERANTO = "eo";
public const string ESTONIAN = "et";
public const string FILIPINO = "tl";
public const string FINNISH = "fi";
public const string FRENCH = "fr";
public const string GALICIAN = "gl";
public const string GEORGIAN = "ka";
public const string GERMAN = "de";
public const string GREEK = "el";
public const string GUARANI = "gn";
public const string GUJARATI = "gu";
public const string HEBREW = "iw";
public const string HINDI = "hi";
public const string HUNGARIAN = "hu";
public const string ICELANDIC = "is";
public const string INDONESIAN = "id";
public const string INUKTITUT = "iu";
public const string ITALIAN = "it";
public const string JAPANESE = "ja";
public const string KANNADA = "kn";
public const string KAZAKH = "kk";
public const string KHMER = "km";
public const string KOREAN = "ko";
public const string KURDISH = "ku";
public const string KYRGYZ = "ky";
public const string LAOTHIAN = "lo";
public const string LATVIAN = "lv";
public const string LITHUANIAN = "lt";
public const string MACEDONIAN = "mk";
public const string MALAY = "ms";
public const string MALAYALAM = "ml";
public const string MALTESE = "mt";
public const string MARATHI = "mr";
public const string MONGOLIAN = "mn";
public const string NEPALI = "ne";
public const string NORWEGIAN = "no";
public const string ORIYA = "or";
public const string PASHTO = "ps";
public const string PERSIAN = "fa";
public const string POLISH = "pl";
public const string PORTUGUESE = "pt-PT";
public const string PUNJABI = "pa";
public const string ROMANIAN = "ro";
public const string RUSSIAN = "ru";
public const string SANSKRIT = "sa";
public const string SERBIAN = "sr";
public const string SINDHI = "sd";
public const string SINHALESE = "si";
public const string SLOVAK = "sk";
public const string SLOVENIAN = "sl";
public const string SPANISH = "es";
public const string SWAHILI = "sw";
public const string SWEDISH = "sv";
public const string TAJIK = "tg";
public const string TAMIL = "ta";
public const string TAGALOG = "tl";
public const string TELUGU = "te";
public const string THAI = "th";
public const string TIBETAN = "bo";
public const string TURKISH = "tr";
public const string UKRAINIAN = "uk";
public const string URDU = "ur";
public const string UZBEK = "uz";
public const string UIGHUR = "ug";
public const string VIETNAMESE = "vi";
public const string UNKNOWN = "";
}
// translatedString =
// Translate(stringToTranslate, Language.ENGLISH, Language.FRENCH);
// Response.Write("<b>French:</b> " + translatedString + "<br/><br/>");
//translatedString =
// Translate(stringToTranslate, Language.ENGLISH, Language.JAPANESE);
//Response.Write("<b>Japanese:</b> " + translatedString + "<br/><br/>");
}
private string Translate(string stringToTranslate, string fromLanguage, string toLanguage)
{
// make sure that the passed string is not empty or null
if (!String.IsNullOrEmpty(stringToTranslate))
{
// per Google's terms of use, we can only translate
// a string of up to 5000 characters long
if (stringToTranslate.Length <= 5000)
{
const int bufSizeMax = 65536;
const int bufSizeMin = 8192;
try
{
// by default format? is text.
// so we don't need to send a format? key
string requestUri = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + stringToTranslate + "&langpair=" + fromLanguage + "%7C" + toLanguage;
// execute the request and get the response stream
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
// get the length of the content returned by the request
int length = (int)response.ContentLength;
int bufSize = bufSizeMin;
// allocate buffer and StringBuilder for reading response
byte[] buf = new byte[bufSize];
StringBuilder sb = new StringBuilder(bufSize);
// read the whole response
while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
{
sb.Append(Encoding.UTF8.GetString(buf, 0, length));
}
// the format of the response is like this
// {"responseData": {"translatedText":"¿Cómo estás?"}, "responseDetails": null, "responseStatus": 200}
// so now let's clean up the response by manipulating the string
string translatedText = sb.Remove(0, 36).ToString();
translatedText = translatedText.Substring(0,
translatedText.IndexOf("\"},"));
return translatedText;
}
catch
{
return "Cannot get the translation. Please try again later.";
}
}
else
{
return "String to translate must be less than 5000 characters long.";
}
}
else
{
return "String to translate is empty.";
}
}
}
but i am not geeting the output.Please help me to complete this task or else inform me where i am going wrong.Plz it's urgent.........
I have tried the above code exactly, But getting the bellow result. Kindly correct my mistake.
Error:
====
Filipino: Cannot get the translation. Please try again later. ========
System.ArgumentOutOfRangeException: Length cannot be less than zero. Parameter name: length at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) at System.String.Substring(Int32 startIndex, Int32 length) at master.Site1.Translate(String
stringToTranslate, String fromLanguage, String toLanguage) in D:\Site1.Master.cs:line 91
FYI: I didn't use any other code except the below code.
Code
=====
public class Language
{
public const string AFRIKAANS = "af";
public const string ALBANIAN = "sq";
public const string AMHARIC = "am";
public const string ARABIC = "ar";
public const string ARMENIAN = "hy";
public const string AZERBAIJANI = "az";
public const string BASQUE = "eu";
public const string BELARUSIAN = "be";
public const string BENGALI = "bn";
public const string BIHARI = "bh";
public const string BULGARIAN = "bg";
public const string BURMESE = "my";
public const string CATALAN = "ca";
public const string CHEROKEE = "chr";
public const string CHINESE = "zh";
public const string CHINESE_SIMPLIFIED = "zh-CN";
public const string CHINESE_TRADITIONAL = "zh-TW";
public const string CROATIAN = "hr";
public const string CZECH = "cs";
public const string DANISH = "da";
public const string DHIVEHI = "dv";
public const string DUTCH = "nl";
public const string ENGLISH = "en";
public const string ESPERANTO = "eo";
public const string ESTONIAN = "et";
public const string FILIPINO = "tl";
public const string FINNISH = "fi";
public const string FRENCH = "fr";
public const string GALICIAN = "gl";
public const string GEORGIAN = "ka";
public const string GERMAN = "de";
public const string GREEK = "el";
public const string GUARANI = "gn";
public const string GUJARATI = "gu";
public const string HEBREW = "iw";
public const string HINDI = "hi";
public const string HUNGARIAN = "hu";
public const string ICELANDIC = "is";
public const string INDONESIAN = "id";
public const string INUKTITUT = "iu";
public const string ITALIAN = "it";
public const string JAPANESE = "ja";
public const string KANNADA = "kn";
public const string KAZAKH = "kk";
public const string KHMER = "km";
public const string KOREAN = "ko";
public const string KURDISH = "ku";
public const string KYRGYZ = "ky";
public const string LAOTHIAN = "lo";
public const string LATVIAN = "lv";
public const string LITHUANIAN = "lt";
public const string MACEDONIAN = "mk";
public const string MALAY = "ms";
public const string MALAYALAM = "ml";
public const string MALTESE = "mt";
public const string MARATHI = "mr";
public const string MONGOLIAN = "mn";
public const string NEPALI = "ne";
public const string NORWEGIAN = "no";
public const string ORIYA = "or";
public const string PASHTO = "ps";
public const string PERSIAN = "fa";
public const string POLISH = "pl";
public const string PORTUGUESE = "pt-PT";
public const string PUNJABI = "pa";
public const string ROMANIAN = "ro";
public const string RUSSIAN = "ru";
public const string SANSKRIT = "sa";
public const string SERBIAN = "sr";
public const string SINDHI = "sd";
public const string SINHALESE = "si";
public const string SLOVAK = "sk";
public const string SLOVENIAN = "sl";
public const string SPANISH = "es";
public const string SWAHILI = "sw";
public const string SWEDISH = "sv";
public const string TAJIK = "tg";
public const string TAMIL = "ta";
public const string TAGALOG = "tl";
public const string TELUGU = "te";
public const string THAI = "th";
public const string TIBETAN = "bo";
public const string TURKISH = "tr";
public const string UKRAINIAN = "uk";
public const string URDU = "ur";
public const string UZBEK = "uz";
public const string UIGHUR = "ug";
public const string VIETNAMESE = "vi";
public const string UNKNOWN = "";
}
public static string Translate(string stringToTranslate, string fromLanguage, string toLanguage)
{
// make sure that the passed string is not empty or null
if (!String.IsNullOrEmpty(stringToTranslate))
{
// per Google's terms of use, we can only translate
// a string of up to 5000 characters long
if (stringToTranslate.Length <= 5000)
{
const int bufSizeMax = 65536;
const int bufSizeMin = 8192;
try
{
// by default format? is text.
// so we don't need to send a format? key
string requestUri = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + stringToTranslate + "&langpair=" + fromLanguage + "%7C" + toLanguage;
// execute the request and get the response stream
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
// get the length of the content returned by the request
int length = (int)response.ContentLength;
int bufSize = bufSizeMin;
// allocate buffer and StringBuilder for reading response
byte[] buf = new byte[bufSize];
StringBuilder sb = new StringBuilder(bufSize);
// read the whole response
while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
{
sb.Append(Encoding.UTF8.GetString(buf, 0, length));
}
// the format of the response is like this
// {"responseData": {"translatedText":"¿Cómo estás?"}, "responseDetails": null, "responseStatus": 200}
// so now let's clean up the response by manipulating the string
string translatedText = sb.Remove(0, 36).ToString();
translatedText = translatedText.Substring(0,translatedText.IndexOf("\"},"));
return translatedText;
}
catch(Exception ex)
{
return "Cannot get the translation. Please try again later. <br> ========<br>" + ex.ToString() + "<br>";
}
}
else
{
return "String to translate must be less than 5000 characters long.";
}
}
else
{
return "String to translate is empty.";
}
}
protected void Page_Load(object sender, EventArgs e)
{
string stringToTranslate = "Where do you live? What's your name? My name is Junnark.";
Response.Write("<b>English:</b> " + stringToTranslate + "<br/><br/>");
shaheen256
Member
45 Points
32 Posts
using google translator with .net
Nov 03, 2009 08:25 AM|LINK
hi
please tell me how to intergate google translator with .net 3.5
with example
.NET 3.5 SP1 google translator
linick
Participant
1268 Points
242 Posts
Re: using google translator with .net
Nov 03, 2009 09:51 AM|LINK
Some useful links:
http://blogs.interakting.co.uk/danmatthews/archive/2008/05/20/Google-Translate-and-.NET.aspx
http://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx
========================================================================
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
shaheen256
Member
45 Points
32 Posts
Re: using google translator with .net
Nov 03, 2009 10:26 AM|LINK
thank you, but the they dont work any more i need new methods
Bober Song -...
All-Star
34686 Points
2167 Posts
Re: using google translator with .net
Nov 06, 2009 02:54 AM|LINK
Hi shaheen256,
I think that's OK.
If you have any error message, please post that.
From my experience. I think you can use HttpWebRequest for requesting that page and passing parameters.
Please double check that code. that will works fine in the .NET version 2.0, 3.0, 3.5.
/// <summary> /// Translate Text using Google Translate API's /// Google URL - http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1} /// </summary> /// <param name="input">Input string</param> /// <param name="languagePair">2 letter Language Pair, delimited by "|". /// E.g. "ar|en" language pair means to translate from Arabic to English</param> /// <returns>Translated to String</returns> public string TranslateText( 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); result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500); result = result.Substring(0, result.IndexOf("</div")); return result; }Let me know whether that answers your question, or if I've missed something.
If you have any feedback about my replies, please contact msdnmg@microsoft.com
Microsoft One Code Framework
shaheen256
Member
45 Points
32 Posts
Re: using google translator with .net
Nov 06, 2009 03:55 AM|LINK
the problem with the above code doesnot return translated text it is actually returning a blank text. thanks for your help. i have found a new way to do this. here is the code
public static class Language
{
public const string AFRIKAANS = "af";
public const string ALBANIAN = "sq";
public const string AMHARIC = "am";
public const string ARABIC = "ar";
public const string ARMENIAN = "hy";
public const string AZERBAIJANI = "az";
public const string BASQUE = "eu";
public const string BELARUSIAN = "be";
public const string BENGALI = "bn";
public const string BIHARI = "bh";
public const string BULGARIAN = "bg";
public const string BURMESE = "my";
public const string CATALAN = "ca";
public const string CHEROKEE = "chr";
public const string CHINESE = "zh";
public const string CHINESE_SIMPLIFIED = "zh-CN";
public const string CHINESE_TRADITIONAL = "zh-TW";
public const string CROATIAN = "hr";
public const string CZECH = "cs";
public const string DANISH = "da";
public const string DHIVEHI = "dv";
public const string DUTCH = "nl";
public const string ENGLISH = "en";
public const string ESPERANTO = "eo";
public const string ESTONIAN = "et";
public const string FILIPINO = "tl";
public const string FINNISH = "fi";
public const string FRENCH = "fr";
public const string GALICIAN = "gl";
public const string GEORGIAN = "ka";
public const string GERMAN = "de";
public const string GREEK = "el";
public const string GUARANI = "gn";
public const string GUJARATI = "gu";
public const string HEBREW = "iw";
public const string HINDI = "hi";
public const string HUNGARIAN = "hu";
public const string ICELANDIC = "is";
public const string INDONESIAN = "id";
public const string INUKTITUT = "iu";
public const string ITALIAN = "it";
public const string JAPANESE = "ja";
public const string KANNADA = "kn";
public const string KAZAKH = "kk";
public const string KHMER = "km";
public const string KOREAN = "ko";
public const string KURDISH = "ku";
public const string KYRGYZ = "ky";
public const string LAOTHIAN = "lo";
public const string LATVIAN = "lv";
public const string LITHUANIAN = "lt";
public const string MACEDONIAN = "mk";
public const string MALAY = "ms";
public const string MALAYALAM = "ml";
public const string MALTESE = "mt";
public const string MARATHI = "mr";
public const string MONGOLIAN = "mn";
public const string NEPALI = "ne";
public const string NORWEGIAN = "no";
public const string ORIYA = "or";
public const string PASHTO = "ps";
public const string PERSIAN = "fa";
public const string POLISH = "pl";
public const string PORTUGUESE = "pt-PT";
public const string PUNJABI = "pa";
public const string ROMANIAN = "ro";
public const string RUSSIAN = "ru";
public const string SANSKRIT = "sa";
public const string SERBIAN = "sr";
public const string SINDHI = "sd";
public const string SINHALESE = "si";
public const string SLOVAK = "sk";
public const string SLOVENIAN = "sl";
public const string SPANISH = "es";
public const string SWAHILI = "sw";
public const string SWEDISH = "sv";
public const string TAJIK = "tg";
public const string TAMIL = "ta";
public const string TAGALOG = "tl";
public const string TELUGU = "te";
public const string THAI = "th";
public const string TIBETAN = "bo";
public const string TURKISH = "tr";
public const string UKRAINIAN = "uk";
public const string URDU = "ur";
public const string UZBEK = "uz";
public const string UIGHUR = "ug";
public const string VIETNAMESE = "vi";
public const string UNKNOWN = "";
public static string Translate(string stringToTranslate, string fromLanguage, string toLanguage)
{
// make sure that the passed string is not empty or null
if (!String.IsNullOrEmpty(stringToTranslate))
{
// per Google's terms of use, we can only translate
// a string of up to 5000 characters long
if (stringToTranslate.Length <= 5000)
{
const int bufSizeMax = 65536;
const int bufSizeMin = 8192;
try
{
// by default format? is text.
// so we don't need to send a format? key
string requestUri = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + stringToTranslate + "&langpair=" + fromLanguage + "%7C" + toLanguage;
// execute the request and get the response stream
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
// get the length of the content returned by the request
int length = (int)response.ContentLength;
int bufSize = bufSizeMin;
if (length > bufSize)
bufSize = length > bufSizeMax ? bufSizeMax : length;
// allocate buffer and StringBuilder for reading response
byte[] buf = new byte[bufSize];
StringBuilder sb = new StringBuilder(bufSize);
// read the whole response
while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
{
sb.Append(Encoding.UTF8.GetString(buf, 0, length));
}
// the format of the response is like this
// {"responseData": {"translatedText":"¿Cómo estás?"}, "responseDetails": null, "responseStatus": 200}
// so now let's clean up the response by manipulating the string
string translatedText = sb.Remove(0, 36).ToString();
translatedText = translatedText.Substring(0,
translatedText.IndexOf("\"},"));
return translatedText;
}
catch
{
return "Cannot get the translation. Please try again later.";
}
}
else
{
return "String to translate must be less than 5000 characters long.";
}
}
else
{
return "String to translate is empty.";
}
}
}
samatha.srir...
Member
110 Points
69 Posts
Re: using google translator with .net
Sep 13, 2010 07:00 AM|LINK
Hi friend,
I am also working on the same.I got the code similar to u.This is my code:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Net;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
public class Language
{
public const string AFRIKAANS = "af";
public const string ALBANIAN = "sq";
public const string AMHARIC = "am";
public const string ARABIC = "ar";
public const string ARMENIAN = "hy";
public const string AZERBAIJANI = "az";
public const string BASQUE = "eu";
public const string BELARUSIAN = "be";
public const string BENGALI = "bn";
public const string BIHARI = "bh";
public const string BULGARIAN = "bg";
public const string BURMESE = "my";
public const string CATALAN = "ca";
public const string CHEROKEE = "chr";
public const string CHINESE = "zh";
public const string CHINESE_SIMPLIFIED = "zh-CN";
public const string CHINESE_TRADITIONAL = "zh-TW";
public const string CROATIAN = "hr";
public const string CZECH = "cs";
public const string DANISH = "da";
public const string DHIVEHI = "dv";
public const string DUTCH = "nl";
public const string ENGLISH = "en";
public const string ESPERANTO = "eo";
public const string ESTONIAN = "et";
public const string FILIPINO = "tl";
public const string FINNISH = "fi";
public const string FRENCH = "fr";
public const string GALICIAN = "gl";
public const string GEORGIAN = "ka";
public const string GERMAN = "de";
public const string GREEK = "el";
public const string GUARANI = "gn";
public const string GUJARATI = "gu";
public const string HEBREW = "iw";
public const string HINDI = "hi";
public const string HUNGARIAN = "hu";
public const string ICELANDIC = "is";
public const string INDONESIAN = "id";
public const string INUKTITUT = "iu";
public const string ITALIAN = "it";
public const string JAPANESE = "ja";
public const string KANNADA = "kn";
public const string KAZAKH = "kk";
public const string KHMER = "km";
public const string KOREAN = "ko";
public const string KURDISH = "ku";
public const string KYRGYZ = "ky";
public const string LAOTHIAN = "lo";
public const string LATVIAN = "lv";
public const string LITHUANIAN = "lt";
public const string MACEDONIAN = "mk";
public const string MALAY = "ms";
public const string MALAYALAM = "ml";
public const string MALTESE = "mt";
public const string MARATHI = "mr";
public const string MONGOLIAN = "mn";
public const string NEPALI = "ne";
public const string NORWEGIAN = "no";
public const string ORIYA = "or";
public const string PASHTO = "ps";
public const string PERSIAN = "fa";
public const string POLISH = "pl";
public const string PORTUGUESE = "pt-PT";
public const string PUNJABI = "pa";
public const string ROMANIAN = "ro";
public const string RUSSIAN = "ru";
public const string SANSKRIT = "sa";
public const string SERBIAN = "sr";
public const string SINDHI = "sd";
public const string SINHALESE = "si";
public const string SLOVAK = "sk";
public const string SLOVENIAN = "sl";
public const string SPANISH = "es";
public const string SWAHILI = "sw";
public const string SWEDISH = "sv";
public const string TAJIK = "tg";
public const string TAMIL = "ta";
public const string TAGALOG = "tl";
public const string TELUGU = "te";
public const string THAI = "th";
public const string TIBETAN = "bo";
public const string TURKISH = "tr";
public const string UKRAINIAN = "uk";
public const string URDU = "ur";
public const string UZBEK = "uz";
public const string UIGHUR = "ug";
public const string VIETNAMESE = "vi";
public const string UNKNOWN = "";
}
protected void Page_Load(object sender, EventArgs e)
{
//string stringToTranslate = txtTranslate.Text;
string stringToTranslate = "Where do you live?";
Response.Write("<b>English:</b> " + stringToTranslate + "<br/><br/>");
string translatedString =
Translate(stringToTranslate, Language.ENGLISH, Language.TELUGU);
translatedString = txtTranslated.Text;
//Response.Write("<b>Telugu:</b> " + translatedString + "<br/><br/>");
// translatedString =
// Translate(stringToTranslate, Language.ENGLISH, Language.SPANISH);
// Response.Write("<b>Spanish:</b> " + translatedString + "<br/><br/>");
// translatedString =
// Translate(stringToTranslate, Language.ENGLISH, Language.CHINESE);
// Response.Write("<b>Chinese:</b> " + translatedString + "<br/><br/>");
// translatedString =
// Translate(stringToTranslate, Language.ENGLISH, Language.FRENCH);
// Response.Write("<b>French:</b> " + translatedString + "<br/><br/>");
//translatedString =
// Translate(stringToTranslate, Language.ENGLISH, Language.JAPANESE);
//Response.Write("<b>Japanese:</b> " + translatedString + "<br/><br/>");
}
private string Translate(string stringToTranslate, string fromLanguage, string toLanguage)
{
// make sure that the passed string is not empty or null
if (!String.IsNullOrEmpty(stringToTranslate))
{
// per Google's terms of use, we can only translate
// a string of up to 5000 characters long
if (stringToTranslate.Length <= 5000)
{
const int bufSizeMax = 65536;
const int bufSizeMin = 8192;
try
{
// by default format? is text.
// so we don't need to send a format? key
string requestUri = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + stringToTranslate + "&langpair=" + fromLanguage + "%7C" + toLanguage;
// execute the request and get the response stream
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
// get the length of the content returned by the request
int length = (int)response.ContentLength;
int bufSize = bufSizeMin;
if (length > bufSize)
bufSize = length > bufSizeMax ? bufSizeMax : length;
// allocate buffer and StringBuilder for reading response
byte[] buf = new byte[bufSize];
StringBuilder sb = new StringBuilder(bufSize);
// read the whole response
while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
{
sb.Append(Encoding.UTF8.GetString(buf, 0, length));
}
// the format of the response is like this
// {"responseData": {"translatedText":"¿Cómo estás?"}, "responseDetails": null, "responseStatus": 200}
// so now let's clean up the response by manipulating the string
string translatedText = sb.Remove(0, 36).ToString();
translatedText = translatedText.Substring(0,
translatedText.IndexOf("\"},"));
return translatedText;
}
catch
{
return "Cannot get the translation. Please try again later.";
}
}
else
{
return "String to translate must be less than 5000 characters long.";
}
}
else
{
return "String to translate is empty.";
}
}
}
but i am not geeting the output.Please help me to complete this task or else inform me where i am going wrong.Plz it's urgent.........
Thanks in advance.....
sathishkumar...
Member
2 Points
2 Posts
Re: using google translator with .net
Jun 03, 2011 06:39 AM|LINK
there are two changes is required to get results.
1. Page_Load()
comment below your line
//translatedString = txtTranslated.Text;
add thie line
txtTranslated.Text= translatedString;
2.About this line, change TELUGU as HINDI. You will get result.Right now, Google is not have Telugu translation service
string translatedString =
Translate(stringToTranslate, Language.ENGLISH, Language.HINDI);
ragu.raguna
Member
2 Points
1 Post
Re: using google translator with .net
Jun 29, 2012 11:53 AM|LINK
Hi shaheen256,
I have tried the above code exactly, But getting the bellow result. Kindly correct my mistake.
Error:
====
Filipino: Cannot get the translation. Please try again later.
========
System.ArgumentOutOfRangeException: Length cannot be less than zero. Parameter name: length at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) at System.String.Substring(Int32 startIndex, Int32 length) at master.Site1.Translate(String stringToTranslate, String fromLanguage, String toLanguage) in D:\Site1.Master.cs:line 91
FYI: I didn't use any other code except the below code.
Code
=====
public class Language
{
public const string AFRIKAANS = "af";
public const string ALBANIAN = "sq";
public const string AMHARIC = "am";
public const string ARABIC = "ar";
public const string ARMENIAN = "hy";
public const string AZERBAIJANI = "az";
public const string BASQUE = "eu";
public const string BELARUSIAN = "be";
public const string BENGALI = "bn";
public const string BIHARI = "bh";
public const string BULGARIAN = "bg";
public const string BURMESE = "my";
public const string CATALAN = "ca";
public const string CHEROKEE = "chr";
public const string CHINESE = "zh";
public const string CHINESE_SIMPLIFIED = "zh-CN";
public const string CHINESE_TRADITIONAL = "zh-TW";
public const string CROATIAN = "hr";
public const string CZECH = "cs";
public const string DANISH = "da";
public const string DHIVEHI = "dv";
public const string DUTCH = "nl";
public const string ENGLISH = "en";
public const string ESPERANTO = "eo";
public const string ESTONIAN = "et";
public const string FILIPINO = "tl";
public const string FINNISH = "fi";
public const string FRENCH = "fr";
public const string GALICIAN = "gl";
public const string GEORGIAN = "ka";
public const string GERMAN = "de";
public const string GREEK = "el";
public const string GUARANI = "gn";
public const string GUJARATI = "gu";
public const string HEBREW = "iw";
public const string HINDI = "hi";
public const string HUNGARIAN = "hu";
public const string ICELANDIC = "is";
public const string INDONESIAN = "id";
public const string INUKTITUT = "iu";
public const string ITALIAN = "it";
public const string JAPANESE = "ja";
public const string KANNADA = "kn";
public const string KAZAKH = "kk";
public const string KHMER = "km";
public const string KOREAN = "ko";
public const string KURDISH = "ku";
public const string KYRGYZ = "ky";
public const string LAOTHIAN = "lo";
public const string LATVIAN = "lv";
public const string LITHUANIAN = "lt";
public const string MACEDONIAN = "mk";
public const string MALAY = "ms";
public const string MALAYALAM = "ml";
public const string MALTESE = "mt";
public const string MARATHI = "mr";
public const string MONGOLIAN = "mn";
public const string NEPALI = "ne";
public const string NORWEGIAN = "no";
public const string ORIYA = "or";
public const string PASHTO = "ps";
public const string PERSIAN = "fa";
public const string POLISH = "pl";
public const string PORTUGUESE = "pt-PT";
public const string PUNJABI = "pa";
public const string ROMANIAN = "ro";
public const string RUSSIAN = "ru";
public const string SANSKRIT = "sa";
public const string SERBIAN = "sr";
public const string SINDHI = "sd";
public const string SINHALESE = "si";
public const string SLOVAK = "sk";
public const string SLOVENIAN = "sl";
public const string SPANISH = "es";
public const string SWAHILI = "sw";
public const string SWEDISH = "sv";
public const string TAJIK = "tg";
public const string TAMIL = "ta";
public const string TAGALOG = "tl";
public const string TELUGU = "te";
public const string THAI = "th";
public const string TIBETAN = "bo";
public const string TURKISH = "tr";
public const string UKRAINIAN = "uk";
public const string URDU = "ur";
public const string UZBEK = "uz";
public const string UIGHUR = "ug";
public const string VIETNAMESE = "vi";
public const string UNKNOWN = "";
}
public static string Translate(string stringToTranslate, string fromLanguage, string toLanguage)
{
// make sure that the passed string is not empty or null
if (!String.IsNullOrEmpty(stringToTranslate))
{
// per Google's terms of use, we can only translate
// a string of up to 5000 characters long
if (stringToTranslate.Length <= 5000)
{
const int bufSizeMax = 65536;
const int bufSizeMin = 8192;
try
{
// by default format? is text.
// so we don't need to send a format? key
string requestUri = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + stringToTranslate + "&langpair=" + fromLanguage + "%7C" + toLanguage;
// execute the request and get the response stream
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
// get the length of the content returned by the request
int length = (int)response.ContentLength;
int bufSize = bufSizeMin;
if (length > bufSize)
bufSize = length > bufSizeMax ? bufSizeMax : length;
// allocate buffer and StringBuilder for reading response
byte[] buf = new byte[bufSize];
StringBuilder sb = new StringBuilder(bufSize);
// read the whole response
while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
{
sb.Append(Encoding.UTF8.GetString(buf, 0, length));
}
// the format of the response is like this
// {"responseData": {"translatedText":"¿Cómo estás?"}, "responseDetails": null, "responseStatus": 200}
// so now let's clean up the response by manipulating the string
string translatedText = sb.Remove(0, 36).ToString();
translatedText = translatedText.Substring(0,translatedText.IndexOf("\"},"));
return translatedText;
}
catch(Exception ex)
{
return "Cannot get the translation. Please try again later. <br> ========<br>" + ex.ToString() + "<br>";
}
}
else
{
return "String to translate must be less than 5000 characters long.";
}
}
else
{
return "String to translate is empty.";
}
}
protected void Page_Load(object sender, EventArgs e)
{
string stringToTranslate = "Where do you live? What's your name? My name is Junnark.";
Response.Write("<b>English:</b> " + stringToTranslate + "<br/><br/>");
string translatedString =
Translate(stringToTranslate, Language.ENGLISH, Language.FILIPINO);
Response.Write("<b>Filipino:</b> " + translatedString + "<br/><br/>");
}
Kindly advice me, Thanks in advance :)
Thanks,
Ragu
Ragunath.S
Asp.net Developer
Chennai