Fredrik von Werder
Sep 27, 2008
  4538
(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
Creating an Optimizely CMS Addon - Adding an Editor Interface Gadget

In   Part One   of this series, I covered getting started with creating your own AddOn for Optimizely CMS 12. This covered what I consider to be an...

Mark Stott | Aug 30, 2024

Configure your own Search & Navigation timeouts

The main blog Configure your own Search & Navigation timeouts was posted for years but you need copy the code to your application. We now bring tho...

Manh Nguyen | Aug 30, 2024

Joining the Optimizely MVP Program

Andy Blyth has been honoured as an Optimizely MVP, recognising his contributions to the Optimizely community. Learn how this achievement will enhan...

Andy Blyth | Aug 29, 2024 | Syndicated blog

Welcome 2024 Summer OMVPs

Hello, Optimizely community! We are thrilled to announce and welcome the newest members to the Optimizely Most Valuable Professionals (OMVP) progra...

Patrick Lam | Aug 29, 2024

Create custom folder type in Edit Mode

Content Folders, which are located in assets pane gadget or multichannel content gadget, allow you to add any type of block or folders. But...

Grzegorz Wiecheć | Aug 28, 2024 | Syndicated blog

Creating an Optimizely AddOn - Getting Started

When Optimizely CMS 12 was launched in the summer of 2021, I created my first AddOn for Optimizely CMS and talked about some of the lessons I learn...

Mark Stott | Aug 28, 2024