using Microsoft.Win32; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Xml.Linq; using System.Web; using System.Windows.Controls; using System.Linq; using System.Diagnostics; namespace Label_Translator { /// /// Логика взаимодействия для MainWindow.xaml /// public partial class MainWindow : Window { private string _content; private const string key = "SECRET_KEY"; public MainWindow() { InitializeComponent(); } private void OpenFileButton (TextBox path, TextBox content) { var ofd = new OpenFileDialog(); ofd.Filter = "Текстовый файл (*.txt) | *.txt"; if ((bool)!ofd.ShowDialog()) return; path.Text = ShowFilePath(ofd); content.Text = ShowFile(ofd); } private string ShowFilePath(OpenFileDialog ofd) => Path.GetFullPath(ofd.FileName); private string ShowFile(OpenFileDialog ofd) { _content = File.ReadAllText(ofd.FileName); return _content; } private void OpenFileButtonRu_Click(object sender, RoutedEventArgs e) => OpenFileButton(ShowFilePathRu, ShowFileRu); private void OpenFileButtonEn_Click(object sender, RoutedEventArgs e) => OpenFileButton(ShowFilePathEn, ShowFileEn); private async void TranslateButton_Click(object sender, RoutedEventArgs e) { var russianWords = new List(); var textWithoutRu = Regex.Replace(_content, "[а-яА-ЯёЁ ]+", m => { if (m.Value == " ") return " "; russianWords.Add(m.Value); return $"{{{russianWords.Count - 1}}}"; }); var translatedRussianWords = await TranslateRussianList(russianWords); ShowFileMod.Text = string.Format(textWithoutRu, translatedRussianWords.ToArray()); } private void SaveButton_Click(object sender, RoutedEventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Текстовый файл (*.txt) | *.txt"; if (sfd.ShowDialog() == true) { File.WriteAllText(sfd.FileName, ShowFileMod.Text); } } private async Task> TranslateRussianList(List words) { var uri = $"https://a...content-available-to-author-only...r.com/translate?api-version=3.0&from=ru&to=en"; object[] body = words.Select(t => new { Text = t }).ToArray(); Debug.WriteLine(body); var RequestBody = JsonConvert.SerializeObject(body); Debug.WriteLine(RequestBody); using (var client = new HttpClient()) using (var request = new HttpRequestMessage()) { request.Method = HttpMethod.Post; request.RequestUri = new Uri(uri); request.Content = new StringContent(RequestBody, Encoding.UTF8, "application/json"); request.Headers.Add("Ocp-Apim-Subscription-Key", key); request.Headers.Add("Ocp-Apim-Subscription-Region", "northeurope"); var response = await client.SendAsync(request); var ResponseBody = await response.Content.ReadAsStringAsync(); Debug.WriteLine(ResponseBody); var result = JsonConvert.DeserializeObject>>>>(ResponseBody); var TranslatedWords = result.Select(t => t["translations"][0]["text"]); return TranslatedWords.ToList(); } } } }