C#-使用两个.txt文件比较/替换文本

本文关键字:文件 txt 比较 文本 替换 两个 C#- | 更新日期: 2023-09-27 18:00:24

我想接受一个文本文件的特定格式。在加载并重新格式化第一个文件后,我想打开第二个文本文件,检查第二个文件是否有与第一个重新格式化的文件匹配的文本。现在我正在成功地将第一个文本文件重新格式化为我想要的格式。第一个(重新格式化的)文本文件如下所示:

    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  
    .
    .
    .

我想知道如何获取这个文件(如上),找到第二列(00100020200020A0030A,…),并在第二个文本文件中进行比较/搜索。第二个文本文件的格式如下:

    10 BARE PCB
    20 T C40, C3112
    B D5, D45, D48
    30 B R25 
    .
    .
    .

一旦我能够从第一个文件(0010002002010030A)和第二个文件(10,20,B,30)中找到匹配,我就想抓住10,20、B,30之后的行,并用它们替换第一个文件00100020020A0030A。此外,如果第一个数字的结尾不是"A"(即0010),我想在新文件的末尾加一个"T"。但是,如果它确实以"A"(即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 

我的代码的一般基础:

  • 打开按钮:打开一个txt文件
  • 保存按钮:将新格式化的文本文件保存到我想要保存的位置
  • 清除按钮:清除我使用的所有富格文本框中的文本
  • OpenRefs按钮:打开用于与第一个文件进行比较的第二个txt文件**

**我还试图让这个按钮将文本的最终格式输出到最终的富文本框中。

这是我当前的代码。

    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);
             }
          }
       }
    }

我有点不知所措。我试着把每一行都记下来,并把它存储在一个字符串列表中,一旦我把两个文件(打开按钮和打开参考按钮)都读到两组列表中,我就要使用string.contents("some_string"),但在文件中,每次我打开不同的文件时,数字都可能出现。我不确定如何正确地迭代每个列表中的每个项来比较字符串(每个"会话"可能不同)。我还打算将它们连接在一起,将最终结果添加到另一个List中,并将其写入最终的富文本框中。然而,我迷失了方向,对C#还很陌生。如有任何帮助,我们将不胜感激。

问题:我如何比较这两个文本文件,将它们正确地放入列表中,比较两个列表中相似的值,用第二个文件中匹配值的以下文本替换第一个文件中的值?如果这令人困惑,请告诉我!

提前感谢!:)

C#-使用两个.txt文件比较/替换文本

如果您的列是用空格或其他字符分隔的,请使用字符串。拆分以形成列阵列。选择所需的列并将其存储在SortedList中(列既是键也是值),每次添加时都要进行检查,以确保没有添加重复项。每次读取第二个文件一行,按SortedList键上的foreach和if字符串。包含键,将该行标记为具有列值之一。

我真的不知道你的记录的格式,因为你说你用空格分割,但你的记录不能正确分割。如果你的文件是一个固定长度的文件,那么你可以使用.substring来提取数据。如果我读对了你的问题,我想你会想阅读第一个文件的每一行,并将其添加到一个哈希集中,使用第二列作为关键字,然后将该行的其余部分作为值。然后循环浏览第二个文件,为行中的每个值找到它所对应的键,并打印该键中的值以及您刚刚读取的行的值。然后,你可以找到一个位置来添加一个条件,如果键有"a"或其他什么,你也可以在末尾打印一个"T"。我认为您应该远离正则表达式,因为性能通常不足,而且我认为这不是您所需要的。

     string strFileName = DisplayFile("Please Select File 1", ".txt", null);
      StreamReader srInput = File.OpenText(strFileName);
      Hashtable newHash = new Hashtable();
      while(srInput.Peek > -1)
      {
            string temp = srInput.ReadLine();
             string parts = temp.Split('//put delimiter here');
             newHash.Add(parts[1]//your key should be your second column                 value,parts              [2]//this is your value);
      }

//然后读取第二个文件并测试每一行,看看它是否与第一个文件匹配。

     string strFileName2 = DisplayFile("Please Select File 2", ".txt", null);
     StreamReader srInput2 = File.OpenText(strFileName);
    while(srInput2.Peek > -1)
    {
   string temp2 = srInput.Readline();
   string[] parts2 = temp2.Split('delim');
   if(newHash.ContainsKey(parts[whichever is the column you want to check is]))
   {
         //then print to value to new file or list
         //newList.Add(parts[that were checked] + newHash[parts that were checked]);
    }
    }

这样的事情会奏效的。