C# 对txt文本行数据进行对比并批量操作

TXT1内容如下
123456 123 甲1
123456 456 甲2
123456 789 甲3
TXT2内容如下
123456 甲2
123456 甲3
TXT3来自TXT2对TXT1的过滤 最后结果如下
123456 甲2 456
123456 甲3 789
该怎么去读取txt1与txt2的内容 进行过滤换位
最后输出txt3?

1 读取txt 

c#使用filestream读取text, 读出来是一行一行的,可以自行组成一个List<string>的

2 对比,

你这个其实就是list1和list2 的分行比较,每次比较一行字符串 看是不是符合你要的规律

 foreach(var line1 in list1) //line1 就是txt1中的某一行

{

     foreach(var line2 in list2)

     {

          if(line2 == line1){} //想怎么比较就怎么比较....

      }

3输出,

 2中你自己写好if之后,符合条件的line1和line2是可以记录下来  组成一个新的list3的,

还是使用filestream  一行一行的输出到txt3中就OK 了。

 public void Read(string path)  //读取txt
        {
            StreamReader sr = new StreamReader(path,Encoding.Default);
            String line;
            while ((line = sr.ReadLine()) != null) 
            {
                Console.WriteLine(line.ToString());
            }
        }
        
      public void Write(string path) //写TXT
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.Write("Hello World!!!!");
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }

追问

有没有完整代码。。 上面那个看过了 用不了= = 不知道问题出在哪。

追答

我刚运行过了,没有问题。
请你发出报错的截图,
代码都是自己写的,能给你的只是思路。

追问

这个问题出在哪?运行后创建出来的txt是空的。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-05-10
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;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string str1, str2;
            string[] arr1 = new string[3];
            string[] arr2 = new string[2];
            StreamReader  sr1,sr2;

            sr1 = File.OpenText(@"D:\1.txt");
            while (!sr1.EndOfStream)
            {
                str1 = sr1.ReadLine();
                arr1 = str1.Split(' ');
                sr2 = File.OpenText(@"D:\2.txt");
                while (!sr2.EndOfStream)
                {
                    str2 = sr2.ReadLine();
                    arr2 = str2.Split(' ');
                    if ((arr1[0] == arr2[0]) && (arr1[2] == arr2[1]))
                    {
                        File.AppendAllText(@"D:\3.txt", str1 + "\r\n");
                    }
                }
                sr2.Close();
                sr2.Dispose();
            }
            sr1.Close();
            sr1.Dispose();
        }
    }
}

本回答被提问者采纳
相似回答