Try our conversational search powered by Generative AI!

Fredrik von Werder
Sep 27, 2008
  4438
(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
The A/A Test: What You Need to Know

Sure, we all know what an A/B test can do. But what is an A/A test? How is it different? With an A/B test, we know that we can take a webpage (our...

Lindsey Rogers | Apr 15, 2024

.Net Core Timezone ID's Windows vs Linux

Hey all, First post here and I would like to talk about Timezone ID's and How Windows and Linux systems use different IDs. We currently run a .NET...

sheider | Apr 15, 2024

What's new in Language Manager 5.3.0

In Language Manager (LM) version 5.2.0, we added an option in appsettings.json called TranslateOrCopyContentAreaChildrenBlockForTypes . It does...

Quoc Anh Nguyen | Apr 15, 2024

Optimizely Search & Navigation: Boosting in Unified Search

In the Optimizely Search & Navigation admin view, administrators can set a certain weight of different properties (title, content, summary, or...

Tung Tran | Apr 15, 2024

Optimizely CMS – Getting all content of a specific property with a simple SQL script

When you need to retrieve all content of a specific property from a Page/Block type, normally you will use the IContentLoader or IContentRepository...

Tung Tran | Apr 15, 2024

Join the Content Recommendations Work Smarter webinar May 8th 16.00-16.45 CET with expert Aidan Swain

Learn more about Content Recommendations, with Optimizely’s very own Senior Solutions consultant, Aidan Swain . He will discuss best practices and...

Karen McDougall | Apr 12, 2024