Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Text.RegularExpressions;
- using Ude;
- namespace Dictionary
- {
- public partial class Form1 : Form
- {
- Dictionary<string, string> dictionary = new Dictionary<string, string>();
- string destinationPath = null; // папка - куда будут записываться измененные файлы
- FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
- OpenFileDialog openFileDialog = new OpenFileDialog
- {
- Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*",
- FilterIndex = 1,
- RestoreDirectory = true,
- Multiselect = false
- }; // просто диалог выбора файла, с настройкой из примера, с сайта msdn
- public Form1()
- {
- InitializeComponent();
- }
- private void openToolStripMenuItem_Click(object sender, EventArgs e)
- {
- dictionary.Clear(); // без этого не айс
- string[] myStringleft = null, myStringRight = null; //массив для левой и правой части датагрида
- myStringleft = OpenFile(); // заполняем массив 1
- myStringRight = OpenFile(); // заполняем массив 2
- if (myStringleft != null && myStringRight != null)
- {
- if (myStringleft.Count() == myStringRight.Count())
- {
- for (int i = 0; i < myStringleft.Count(); i++)
- {
- dictionary.Add(myStringleft[i], myStringRight[i]);
- }
- if (destinationPath != null && dictionary.Count != 0)
- {
- replaceFromLeftToolStripMenuItem.Enabled = true;
- replaceFromRightToolStripMenuItem.Enabled = true;
- }
- BindingSource bindingSource = new BindingSource
- {
- DataSource = dictionary // применяем словарь сюда
- }; //нельзя просто взять словарь и показать
- dataGridView1.DataSource = bindingSource; // и только теперь показываем
- dataGridView1.Refresh(); // на всякий случай обновляем датагрид
- }//проверяем кол-во строк, если одинаково, то заполняем словарь, нет, идем в лес ыыы
- else
- {
- MessageBox.Show("У файлов разное кол-во строк!Так не пойдёт!");
- }
- } //берем два файла и пихаем в словарь
- }
- private void ExchangeStrings(char LR)
- {
- bool CheckString(string a, string b)
- {
- return a != b;
- }
- string[] fileNames = null;
- if (dictionary.Count > 0) //реагируем на кнопку только после загрузки словаря
- {
- string[] leftPart = null;
- string[] rightPart = null;
- leftPart = dictionary.Keys.ToArray(); //левая часть датагрида
- rightPart = dictionary.Values.ToArray();//правая часть датагрида
- folderBrowserDialog.Description = "Set source path";
- if (folderBrowserDialog.ShowDialog() == DialogResult.OK) //указываем папку с файлами, где нужно заменить по словарю
- {
- fileNames = Directory.GetFiles(folderBrowserDialog.SelectedPath);//получаем список файлов по указанному пути, вместе с путями и расширением
- for (int i = 0; i < fileNames.Length; i++)
- {
- if (Path.GetExtension(fileNames[i]) != ".txt" && Path.GetExtension(fileNames[i]) != ".lng") //в указанной папке будем трогать только txt файлы
- {
- fileNames[i] = null;
- }
- }
- for (int k = 0; k < fileNames.Length; k++) //цикл по файлам
- {
- string[] tmpString = null;// оригинальный файл
- string[] tmpStringChanged = null;//измененный файл, для сохранения
- if (fileNames[k] != null) // если есть путь, то загружаем файл и ищем по словарю
- {
- try
- {
- tmpString = File.ReadAllLines(fileNames[k],Encoding.GetEncoding(CheckEncoding(fileNames[k])));//строки из файла в массив
- tmpStringChanged = tmpString; // немного костылей, чтоб не париться с размером массива
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
- }
- for (int j = 0; j < tmpString.Length; j++) //цикл по строкам из файла
- {
- for (int r = 0; r < dictionary.Count; r++) //каждую строку смотрим столько раз,сколько есть в словаре
- {
- if (LR == 'L')//если в метод передан чар Л, то пользователь нажал Replace from left,
- //то ищем слово из правой части и меняем словом из левой части
- {
- tmpStringChanged[j] = Regex.Replace(tmpString[j], rightPart[r], leftPart[r]);//где искать,что искать,чем менять
- if (CheckString(tmpString[j], tmpStringChanged[j])) //если строки не равны - выходим
- {
- break;
- }
- }
- else
- {
- tmpStringChanged[j] = Regex.Replace(tmpString[j], leftPart[r], rightPart[r]);
- if (CheckString(tmpString[j], tmpStringChanged[j]))
- {
- break;
- }
- }
- }
- }
- //сохраняем измененный массив по пути, с оригинальным именем файла и расширением
- SaveChangedFile(tmpStringChanged, destinationPath, Path.GetFileName(fileNames[k]));
- tmpString = null;
- tmpStringChanged = null;
- }
- }
- MessageBox.Show("All files converted!");
- }
- }
- else
- {
- MessageBox.Show("Заполните словарь! Нажмите 'Open' и выберите два файла");
- }
- } // метод который будет искать и менять в зависимости от нажатой кнопки
- private string CheckEncoding(string path)
- {
- CharsetDetector cDetector = new CharsetDetector();
- using (FileStream fs = File.OpenRead(path))
- {
- cDetector.Feed(fs);
- cDetector.DataEnd();
- fs.Close();
- }
- return cDetector.Charset;
- }
- private void SaveChangedFile(string[] content, string path, string fileName)
- {
- int CheckEncoding(string[] tmpContent)
- {
- foreach (string a in tmpContent)
- {
- if (a.Contains("о") || a.Contains("щ") || a.Contains("ы") || a.Contains("п") || a.Contains("я") || a.Contains("р"))
- {
- return 1251;
- }
- else
- {
- return 65001;
- }
- }
- return 65001;
- }
- //Encoding ANSI = Encoding.GetEncoding(1251);
- //Encoding UTF16LE = Encoding.Unicode;
- //byte[] ansiBytes = null, utfBytes = null;
- //for (int i = 0; i < content.Length; i++)
- //{
- // utfBytes = UTF16LE.GetBytes(content[i]);
- //}
- try
- {
- //StreamWriter writer = new StreamWriter((Path.Combine(path,fileName)), false, Encoding.GetEncoding(1251));
- //for (int i = 0; i < content.Length; i++)
- //{
- // writer.Write(content[i]);
- //}
- //writer.Close();
- File.WriteAllLines(Path.Combine(path, fileName), content, Encoding.GetEncoding(CheckEncoding(content)));
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- } // сохраняем файлы
- private string[] OpenFile()
- {
- //CharsetDetector charsetDetector = new CharsetDetector();
- //if (openFileDialog.ShowDialog() == DialogResult.OK)
- //{
- // using (FileStream fs = File.OpenRead(openFileDialog.FileName))
- // {
- // charsetDetector.Feed(fs);
- // charsetDetector.DataEnd();
- // fs.Close();
- // }
- //}
- string[] tmpString = null;
- if (openFileDialog.ShowDialog() == DialogResult.OK)
- {
- try
- {
- tmpString = File.ReadAllLines(openFileDialog.FileName, Encoding.GetEncoding(CheckEncoding(openFileDialog.FileName)));
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
- }
- }
- return tmpString;
- } //открываем файлы
- private void replaceFromLeftToolStripMenuItem_Click(object sender, EventArgs e)
- {
- ExchangeStrings('L');
- } //просто вызываем метод ExchangeStrings с чаром L
- private void replaceFromRightToolStripMenuItem_Click(object sender, EventArgs e)
- {
- ExchangeStrings('R');
- } //просто вызываем метод ExchangeStrings с чаром R
- private void setDestinationFolderToolStripMenuItem_Click(object sender, EventArgs e)
- {
- if (folderBrowserDialog.ShowDialog() == DialogResult.OK) //указываем папку с файлами, где нужно заменить по словарю
- {
- folderBrowserDialog.Description = "Set destination path";
- destinationPath = folderBrowserDialog.SelectedPath;
- label1.Text = destinationPath;
- if (destinationPath != null && dictionary.Count != 0)
- {
- replaceFromLeftToolStripMenuItem.Enabled = true;
- replaceFromRightToolStripMenuItem.Enabled = true;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement