Try our conversational search powered by Generative AI!

Fredrik von Werder
Sep 27, 2008
  4489
(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 Search and Navigation - Part 2 - Filter Tips

Introduction Continuing from Part 1 – Search Tips , today I will share the next part – filter tips. The platform versions used for this article are...

Binh Nguyen Thi | Jul 1, 2024

Integrating HubSpot CRM without the MA Connector

Have HubSpot CRM? Want to push user data into it from Optimizely? Don’t have any personalisation requirements with that data? Don’t want to pay $80...

Matt Pallatt | Jun 27, 2024

Keeping the website secure by updating external packages

Did you see the latest warning from Optimizely to update this package with a critical security warning? https://world.optimizely.com/documentation/...

Daniel Ovaska | Jun 27, 2024

Optimizely CMS image anonymization now available for Linux!

The famous image anonymization add-on for Optimizely CMS, with at least 5 downloads, is now finally available for use on Linux. Supports simultaneo...

Tomas Hensrud Gulla | Jun 25, 2024 | Syndicated blog