Try our conversational search powered by Generative AI!

Fredrik von Werder
Sep 27, 2008
  4456
(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
Configured Commerce - Infrastructure Updates Ahoy!

I'm very happy to share an important milestone - we no longer have any customers in our legacy v1 environment!  This means that the Configured...

John McCarroll | May 10, 2024

A day in the life of an Optimizely Developer - Enabling Opti ID within your application

Hello and welcome to another instalment of A Day In The Life Of An Optimizely developer, in this blog post I will provide details on Optimizely's...

Graham Carr | May 9, 2024

How to add a custom property in Optimizely Graph

In the Optimizely CMS content can be synchronized to the Optimizely Graph service for it then to be exposed by the GraphQL API. In some cases, you...

Ynze | May 9, 2024 | Syndicated blog

New Security Improvement released for Optimizely CMS 11

A new security improvement has been released for Optimizely CMS 11. You should update now!

Tomas Hensrud Gulla | May 7, 2024 | Syndicated blog

Azure AI Language – Key Phrase Extraction in Optimizely CMS

In this article, I demonstrate how the key phrase extraction feature, offered by the Azure AI Language service, can be used to generate a list of k...

Anil Patel | May 7, 2024 | Syndicated blog

Webinar: Get Started with AI within Optimizely CMS

Join us for the webinar "Get Started with AI in Optimizely CMS" on Wednesday, May 8th. Don't forget to register!

Luc Gosso (MVP) | May 7, 2024 | Syndicated blog