Я хочу взять в определенном формате один текстовый файл.После того, как первый файл загружен и переформатирован, я хочу открыть второй текстовый файл и проверить, есть ли во втором файле текстовые совпадения с первым переформатированным файлом.Прямо сейчас я успешно переформатирую первый текстовый файл так, как я хочу.Первый (переформатированный) текстовый файл выглядит следующим образом:
1 0010 12345 DEF, DEF-0320
1 0020 ABC-00010G ABC-A,1xx,10%,x1x,0603
1 0020A ABC-00010G ABC-A,1xx,10%,x1x,0603
1 0030A ABC-00127G ABC,4.7xx,10%,x1x,0805
.
.
.
Я хочу знать, как взять этот файл (см. Выше) и найти второй столбец (0010, 0020, 0020A, 0030A, ...)и сравните его / найдите его во втором текстовом файле.Формат для второго текстового файла будет выглядеть примерно так:
10 BARE PCB
20 T C40, C3112
B D5, D45, D48
30 B R25
.
.
.
Как только я смогу найти совпадение из первого файла (0010, 0020, 0020A, 0030A) со вторым файлом (10,20, B, 30) Я хочу взять строки после 10, 20, B, 30 и заменить первые файлы 0010, 0020, 0020A, 0030A ими.Кроме того, если число от первого не заканчивается на «A» (то есть 0010), я хочу поставить «T» в конце нового файла.Однако, если он заканчивается буквой «А» (т. Е. 0030A), я хочу поставить букву «B» в конце файла.Кроме того, для каждого значения во втором файле, который имеет формат «C40» (или аналогичный), я хочу поместить на новую строку, если есть несколько (разделенных «,»), и скопировать ту же информацию из вышеуказанной строки,Это означает, что это будет выглядеть так:
1 AAAA BCD 12345 DEF, DEF-0320 T
1 C40 ABC-00010G ABC-A,1xx,10%,x1x,0603 T
1 C3112 ABC-00010G ABC-A,1xx,10%,x1x,0603 T
1 D5 ABC-00010G ABC-A,1xx,20%,x1x,0603 B
1 D45 ABC-00010G ABC-A,1xx,20%,x1x,0603 B
1 D48 ABC-00010G ABC-A,1xx,20%,x1x,0603 B
1 R25 ABC-00127G ABC,4.7xx,100%,x1x,0805 B
Общая основа моего кода:
- Кнопка открытия: открывает текстовый файл.
- Кнопка сохранения: сохраняетновый отформатированный текстовый файл, куда я всегда хочу его сохранить.
- Кнопка «Очистить»: очищает текст во всех используемых мной текстовых полях.
- Кнопка «OpenRefs»: открывает второй текстовый файл.используется для сравнения с первым файлом. **
** Я также пытаюсь получить эту кнопку для вывода окончательного форматирования текста в окончательное поле расширенного текста.
Вот мой текущий код.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace Formatter
{
public partial class Form : Form
{
// Create a OpenFileDialog to request a path and file name to open.
OpenFileDialog openFile = new OpenFileDialog();
OpenFileDialog openRefs = new OpenFileDialog();
public Form()
{
InitializeComponent();
}
private void openButton_Click(object sender, EventArgs e)
{
// Initialize the OpenFileDialog to specify the .txt extension as well as
// its intial directory for the file.
openFile.DefaultExt = "*.txt";
openFile.Filter = ".txt Files|*.txt";
openFile.InitialDirectory = "C:\\";
openFile.RestoreDirectory = true;
try
{
// Open the contents of the file into the originalTextRichTextBox.
if (openFile.ShowDialog() == DialogResult.OK && openFile.FileName.Length > 0)
originalTextRichTextBox.LoadFile(openFile.FileName, RichTextBoxStreamType.PlainText);
// Throws a FileNotFoundException otherwise.
else
throw new FileNotFoundException();
// Resets the formattedTextRichTextBox so multiple files aren't loaded on top of eachother.
formattedTextRichTextBox.ResetText();
foreach (string line in File.ReadAllLines(openFile.FileName))
{
// Uses regular expressions to find a line that has, digit(s), space(s), digit(s) + letter(s),
// space(s), digit(s), space(s), any character (up to 25 times).
Match theMatch = Regex.Match(line, @"^[\.*\d]+\s+[\d\w]+\s+[\d\-\w*]+\s+.{25}");
if (theMatch.Success)
{
// Stores the matched value in string output.
string output = theMatch.Value;
// Sets the formattedTextRichTextBox to the string output.
formattedTextRichTextBox.AppendText(output);
formattedTextRichTextBox.AppendText("\n");
}
}
}
// Catches an exception if the file was not opened.
catch (Exception)
{
MessageBox.Show("There was not a specified file path.", "Path Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void saveButton_Click(object sender, EventArgs e)
{
// Create a SaveFileDialog to request a path and file name to save.
SaveFileDialog saveFile = new SaveFileDialog();
// Initialize the SaveFileDialog to specify the .txt extension for the file.
saveFile.DefaultExt = "*.txt";
saveFile.Filter = ".txt Files|*.txt";
saveFile.InitialDirectory = "C:\\";
saveFile.RestoreDirectory = true;
try
{
// Save the contents of the formattedTextRichTextBox into the file.
if (saveFile.ShowDialog() == DialogResult.OK && saveFile.FileName.Length > 0)
formattedTextRichTextBox.SaveFile(saveFile.FileName, RichTextBoxStreamType.PlainText);
// Throws a FileNotFoundException otherwise.
else
throw new FileNotFoundException();
}
// Catches an exception if the file was not saved.
catch (Exception)
{
MessageBox.Show("There was not a specified file path.", "Path Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void clearButton_Click(object sender, EventArgs e)
{
try
{
// Resets the text in all of the boxes.
originalTextRichTextBox.ResetText();
formattedTextRichTextBox.ResetText();
refsTextRichTextBox.ResetText();
finalTextRichTextBox.ResetText();
}
// Catches an exception if the either text box could not be cleared.
catch (Exception)
{
MessageBox.Show("Could not clear the text.", "Clearing Text Box Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void openRefsButton_Click(object sender, EventArgs e)
{
// Initialize the OpenFileDialog to specify the .txt extension as well as
// its intial directory for the file.
openRefs.DefaultExt = "*.txt";
openRefs.Filter = ".txt Files|*.txt";
openRefs.InitialDirectory = "C:\\";
openRefs.RestoreDirectory = true;
try
{
// Open the contents of the file into the originalTextRichTextBox.
if (openRefs.ShowDialog() == DialogResult.OK && openRefs.FileName.Length > 0)
refsTextRichTextBox.LoadFile(openRefs.FileName, RichTextBoxStreamType.PlainText);
// Throws a FileNotFoundException otherwise.
else
throw new FileNotFoundException();
// ********************************************
// ********************************************
// ********************************************
// FROM HERE DOWN IS WHERE I NEED THE HELP! :)
// ********************************************
// ********************************************
// ********************************************
string[] refLines = System.IO.File.ReadAllLines(openRefs.FileName);
foreach (string line in refLines)
{
finalTextRichTextBox.AppendText(line + "\n");
}
try
{
using (StreamReader readRefs = new StreamReader(openRefs.FileName))
{
originalTextRichTextBox.ResetText();
List<string> refFileLines = new List<string>();
while (!readRefs.EndOfStream)
{
refFileLines.Add(readRefs.ReadLine());
}
using (StreamReader readFile = new StreamReader(openFile.FileName))
{
List<string> fileLines = new List<string>();
while (!readFile.EndOfStream)
{
fileLines.Add(readFile.ReadLine());
}
}
refFileLines.Contains("");
}
}
catch (Exception)
{
MessageBox.Show("Could not read file.", "Read File Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
// Catches an exception if the file was not opened.
catch (Exception)
{
MessageBox.Show("There was not a specified file path.", "Path Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
Я немного растерялся из-за того, что делать.Я пытался взять каждую строку и сохранить ее в списке строк, и как только я прочитал оба файла (кнопка открытия и кнопка openrefs) в два набора списка, я собирался использовать string.contains («some_string»), но вфайлы, номера могут каждый раз, когда я открываю другой файл.Я не уверен, как бы я мог выполнить итерацию правильно, хотя каждый элемент в каждом списке для сравнения строк (которые могут отличаться в каждой «сессии»).Я также собирался объединить их вместе и добавить окончательный результат в другой список и записать его в окончательное поле расширенного текста.Тем не менее, я заблудился и довольно плохо знаком с C #.Любая помощь будет принята с благодарностью.
Вопрос: Как я могу сравнить эти два текстовых файла, правильно поместить их в список, сравнить два списка для сходных значений, заменить значения в первом файле наследующий текст из сопоставленных значений во втором файле?Если это сбивает с толку, дайте мне знать!
Заранее спасибо!:)