Advertisement
Guest User

Untitled

a guest
Jun 13th, 2018
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.38 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Windows.Forms;
  7. using System.Text.RegularExpressions;
  8. using Ude;
  9.  
  10. namespace Dictionary
  11. {
  12.     public partial class Form1 : Form
  13.     {
  14.         Dictionary<string, string> dictionary = new Dictionary<string, string>();
  15.         string destinationPath = null; // папка - куда будут записываться измененные файлы
  16.         FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
  17.         OpenFileDialog openFileDialog = new OpenFileDialog
  18.         {
  19.             Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*",
  20.             FilterIndex = 1,
  21.             RestoreDirectory = true,
  22.             Multiselect = false
  23.         }; // просто диалог выбора файла, с настройкой из примера, с сайта msdn
  24.         public Form1()
  25.         {
  26.             InitializeComponent();
  27.         }
  28.  
  29.         private void openToolStripMenuItem_Click(object sender, EventArgs e)
  30.         {
  31.             dictionary.Clear(); // без этого не айс
  32.             string[] myStringleft = null, myStringRight = null; //массив для левой и правой части датагрида
  33.             myStringleft = OpenFile(); // заполняем массив 1
  34.             myStringRight = OpenFile(); // заполняем массив 2
  35.             if (myStringleft != null && myStringRight != null)
  36.             {
  37.                 if (myStringleft.Count() == myStringRight.Count())
  38.                 {
  39.                     for (int i = 0; i < myStringleft.Count(); i++)
  40.                     {
  41.                         dictionary.Add(myStringleft[i], myStringRight[i]);
  42.                     }
  43.                     if (destinationPath != null && dictionary.Count != 0)
  44.                     {
  45.                         replaceFromLeftToolStripMenuItem.Enabled = true;
  46.                         replaceFromRightToolStripMenuItem.Enabled = true;
  47.                     }
  48.                     BindingSource bindingSource = new BindingSource
  49.                     {
  50.                         DataSource = dictionary // применяем словарь сюда
  51.                     }; //нельзя просто взять словарь и показать
  52.                     dataGridView1.DataSource = bindingSource; // и только теперь показываем
  53.                     dataGridView1.Refresh(); // на всякий случай обновляем  датагрид
  54.                 }//проверяем кол-во строк, если одинаково, то заполняем словарь, нет, идем в лес ыыы
  55.                 else
  56.                 {
  57.                     MessageBox.Show("У файлов разное кол-во строк!Так не пойдёт!");
  58.                 }
  59.  
  60.             } //берем два файла и пихаем в словарь
  61.         }
  62.  
  63.         private void ExchangeStrings(char LR)
  64.         {
  65.             bool CheckString(string a, string b)
  66.             {
  67.                 return a != b;
  68.             }
  69.             string[] fileNames = null;
  70.             if (dictionary.Count > 0) //реагируем на кнопку только после загрузки словаря
  71.             {
  72.                 string[] leftPart = null;
  73.                 string[] rightPart = null;
  74.                 leftPart = dictionary.Keys.ToArray(); //левая часть датагрида
  75.                 rightPart = dictionary.Values.ToArray();//правая часть датагрида
  76.                 folderBrowserDialog.Description = "Set source path";
  77.                 if (folderBrowserDialog.ShowDialog() == DialogResult.OK) //указываем папку с файлами, где нужно заменить по словарю
  78.                 {
  79.                     fileNames = Directory.GetFiles(folderBrowserDialog.SelectedPath);//получаем список файлов по указанному пути, вместе с путями и расширением
  80.                     for (int i = 0; i < fileNames.Length; i++)
  81.                     {
  82.                         if (Path.GetExtension(fileNames[i]) != ".txt" && Path.GetExtension(fileNames[i]) != ".lng") //в указанной папке будем трогать только txt файлы
  83.                         {
  84.                             fileNames[i] = null;
  85.                         }
  86.                     }
  87.                     for (int k = 0; k < fileNames.Length; k++) //цикл по файлам
  88.                     {
  89.                         string[] tmpString = null;// оригинальный файл
  90.                         string[] tmpStringChanged = null;//измененный файл, для сохранения
  91.  
  92.                         if (fileNames[k] != null) // если есть путь, то загружаем файл и ищем по словарю
  93.                         {
  94.                             try
  95.                             {
  96.                                 tmpString = File.ReadAllLines(fileNames[k],Encoding.GetEncoding(CheckEncoding(fileNames[k])));//строки из файла в массив
  97.                                 tmpStringChanged = tmpString; // немного костылей, чтоб не париться с размером массива
  98.                             }
  99.                             catch (Exception ex)
  100.                             {
  101.                                 MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
  102.                             }
  103.                             for (int j = 0; j < tmpString.Length; j++) //цикл по строкам из файла
  104.                             {
  105.                                 for (int r = 0; r < dictionary.Count; r++) //каждую строку смотрим столько раз,сколько есть в словаре
  106.                                 {
  107.                                     if (LR == 'L')//если в метод передан чар Л, то пользователь нажал Replace from left,
  108.                                                   //то ищем слово из правой части и меняем словом из левой части
  109.                                     {
  110.                                         tmpStringChanged[j] = Regex.Replace(tmpString[j], rightPart[r], leftPart[r]);//где искать,что искать,чем менять
  111.                                         if (CheckString(tmpString[j], tmpStringChanged[j])) //если строки не равны - выходим
  112.                                         {
  113.                                             break;
  114.                                         }
  115.                                     }
  116.                                     else
  117.                                     {
  118.                                         tmpStringChanged[j] = Regex.Replace(tmpString[j], leftPart[r], rightPart[r]);
  119.                                         if (CheckString(tmpString[j], tmpStringChanged[j]))
  120.                                         {
  121.                                             break;
  122.                                         }
  123.                                     }
  124.                                 }
  125.                             }
  126.                             //сохраняем измененный массив по пути, с оригинальным именем файла и расширением
  127.                             SaveChangedFile(tmpStringChanged, destinationPath, Path.GetFileName(fileNames[k]));
  128.                             tmpString = null;
  129.                             tmpStringChanged = null;
  130.                         }
  131.                     }
  132.                    
  133.                     MessageBox.Show("All files converted!");
  134.                 }
  135.             }
  136.             else
  137.             {
  138.                 MessageBox.Show("Заполните словарь! Нажмите 'Open' и выберите два файла");
  139.             }
  140.         } // метод который будет искать и менять в зависимости от нажатой кнопки
  141.  
  142.         private string CheckEncoding(string path)
  143.         {
  144.             CharsetDetector cDetector = new CharsetDetector();
  145.             using (FileStream fs = File.OpenRead(path))
  146.             {
  147.                 cDetector.Feed(fs);
  148.                 cDetector.DataEnd();
  149.                 fs.Close();
  150.             }
  151.             return cDetector.Charset;
  152.         }
  153.  
  154.         private void SaveChangedFile(string[] content, string path, string fileName)
  155.         {
  156.             int CheckEncoding(string[] tmpContent)
  157.             {
  158.                 foreach (string a in tmpContent)
  159.                 {
  160.                     if (a.Contains("о") || a.Contains("щ") || a.Contains("ы") || a.Contains("п") || a.Contains("я") || a.Contains("р"))
  161.                     {
  162.                         return 1251;
  163.                     }
  164.                     else
  165.                     {
  166.                         return 65001;
  167.                     }
  168.                 }
  169.                 return 65001;
  170.             }
  171.             //Encoding ANSI = Encoding.GetEncoding(1251);
  172.             //Encoding UTF16LE = Encoding.Unicode;
  173.             //byte[] ansiBytes = null, utfBytes = null;
  174.             //for (int i = 0; i < content.Length; i++)
  175.             //{
  176.             //    utfBytes = UTF16LE.GetBytes(content[i]);
  177.             //}
  178.  
  179.             try
  180.             {
  181.                 //StreamWriter writer = new StreamWriter((Path.Combine(path,fileName)), false, Encoding.GetEncoding(1251));
  182.                 //for (int i = 0; i < content.Length; i++)
  183.                 //{
  184.                 //    writer.Write(content[i]);
  185.                 //}
  186.                 //writer.Close();
  187.                 File.WriteAllLines(Path.Combine(path, fileName), content, Encoding.GetEncoding(CheckEncoding(content)));
  188.             }
  189.             catch (Exception ex)
  190.             {
  191.                 MessageBox.Show(ex.Message);
  192.             }
  193.         } // сохраняем файлы
  194.  
  195.         private string[] OpenFile()
  196.         {
  197.             //CharsetDetector charsetDetector = new CharsetDetector();
  198.             //if (openFileDialog.ShowDialog() == DialogResult.OK)
  199.             //{
  200.             //    using (FileStream fs = File.OpenRead(openFileDialog.FileName))
  201.             //    {
  202.             //        charsetDetector.Feed(fs);
  203.             //        charsetDetector.DataEnd();
  204.             //        fs.Close();
  205.             //    }
  206.             //}
  207.             string[] tmpString = null;
  208.             if (openFileDialog.ShowDialog() == DialogResult.OK)
  209.             {
  210.                 try
  211.                 {
  212.                     tmpString = File.ReadAllLines(openFileDialog.FileName, Encoding.GetEncoding(CheckEncoding(openFileDialog.FileName)));
  213.                 }
  214.                 catch (Exception ex)
  215.                 {
  216.                     MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
  217.                 }
  218.             }
  219.             return tmpString;
  220.         } //открываем файлы
  221.  
  222.         private void replaceFromLeftToolStripMenuItem_Click(object sender, EventArgs e)
  223.         {
  224.             ExchangeStrings('L');
  225.         } //просто вызываем метод ExchangeStrings с чаром L
  226.  
  227.         private void replaceFromRightToolStripMenuItem_Click(object sender, EventArgs e)
  228.         {
  229.             ExchangeStrings('R');
  230.         } //просто вызываем метод ExchangeStrings с чаром R
  231.  
  232.         private void setDestinationFolderToolStripMenuItem_Click(object sender, EventArgs e)
  233.         {
  234.             if (folderBrowserDialog.ShowDialog() == DialogResult.OK) //указываем папку с файлами, где нужно заменить по словарю
  235.             {
  236.                 folderBrowserDialog.Description = "Set destination path";
  237.                 destinationPath = folderBrowserDialog.SelectedPath;
  238.                 label1.Text = destinationPath;
  239.                 if (destinationPath != null && dictionary.Count != 0)
  240.                 {
  241.                     replaceFromLeftToolStripMenuItem.Enabled = true;
  242.                     replaceFromRightToolStripMenuItem.Enabled = true;
  243.                 }
  244.             }
  245.         }
  246.     }
  247. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement