Пример #1
0
        /// <summary>
        /// Converts a language to its identifier.
        /// </summary>
        /// <param name="language">The language."</param>
        /// <returns>The identifier or <see cref="string.Empty"/> if none.</returns>
        private static string LanguageEnumToIdentifier
            (string language)
        {
            string mode = string.Empty;

            GoogleTranslator.EnsureInitialized();
            GoogleTranslator._languageModeMap.TryGetValue(language, out mode);
            return(mode);
        }
Пример #2
0
        /// <summary>
        /// Translates the specified source text.
        /// </summary>
        /// <param name="sourceText">The source text.</param>
        /// <param name="sourceLanguage">The source language.</param>
        /// <param name="targetLanguage">The target language.</param>
        /// <returns>The translation.</returns>
        public async Task <string> Translate
            (string sourceText,
            string sourceLanguage,
            string targetLanguage)
        {
            // Initialize
            DateTime tmStart = DateTime.Now;
            string   text    = string.Empty;
            // Download translation
            string url = string.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
                                       GoogleTranslator.LanguageEnumToIdentifier(sourceLanguage),
                                       GoogleTranslator.LanguageEnumToIdentifier(targetLanguage),
                                       HttpUtility.UrlEncode(sourceText));

            using (HttpClient http = new HttpClient())
            {
                http.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
                text = await http.GetStringAsync(url).ConfigureAwait(false);
            }

            // Return result
            return(string.Concat(JArray.Parse(text)[0].Select(x => x[0])));
        }