Don't miss out Virtual Happy Hour today (April 26).

Try our conversational search powered by Generative AI!

Fredrik von Werder
Sep 27, 2008
  4445
(0 votes)

ASP.NET 3.5 Extension - Translate a String

Using Google translations, translate a string to (almost) any language.

Since it is an extension, it will be available like myString.Translate("sv","en"); but you can of course use it as a regular method by removing the arg 'this string s'.

Note that the web server must be able to make web requests to google.com.

You can use both codes like "en" or the culture and lang "sv-SE" version (takes the first one)

C# code:

using System;
using System.Text;
using System.Net;
public static string Translate(this string s, string langFrom, string langTo)
        {
            if (String.IsNullOrEmpty(s))
                return String.Empty;

            if (langFrom.Contains("-"))
                langFrom = langFrom.Split('-')[0];

            if (langTo.Contains("-"))
                langTo = langTo.Split('-')[0];

            string address = string.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}%7C{2}", s, langFrom, langTo);
            string html = new WebClient().DownloadString(address);
            string block = html.Substring(html.IndexOf("id=result_box") + 0x18, 500);
            string phrase = block.Substring(0, block.IndexOf("</div"));
            return phrase;         
        }
 
Sep 27, 2008

Comments

Please login to comment.
Latest blogs
Optimizely Unit Testing Using CmsContentScaffolding Package

Introduction Unit tests shouldn't be created just for business logic, but also for the content and rules defined for content creation (available...

MilosR | Apr 26, 2024

Solving the mystery of high memory usage

Sometimes, my work is easy, the problem could be resolved with one look (when I’m lucky enough to look at where it needs to be looked, just like th...

Quan Mai | Apr 22, 2024 | Syndicated blog

Search & Navigation reporting improvements

From version 16.1.0 there are some updates on the statistics pages: Add pagination to search phrase list Allows choosing a custom date range to get...

Phong | Apr 22, 2024

Optimizely and the never-ending story of the missing globe!

I've worked with Optimizely CMS for 14 years, and there are two things I'm obsessed with: Link validation and the globe that keeps disappearing on...

Tomas Hensrud Gulla | Apr 18, 2024 | Syndicated blog