C# 读取TXT文本文档 搜索指定字符串所在的行 保存到集合

1.先拖一个按钮到主界面里,如下图

 

2.添加一个Click事件(或者直接双击按钮)

using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

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

        List<string> ZZZString = new List<string>();//定义一个集合,用于储存数据


        //创建一个Click事件,用于打开读取文件
        private void button1_Click(object sender, System.EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog objOpenFile = new System.Windows.Forms.OpenFileDialog();
            objOpenFile.Filter = "文本文档|*.txt";

            if (objOpenFile.ShowDialog() == DialogResult.OK)
            {
                //this.txtFile.Text = objOpenFile.FileName;
                string[] ReadText = File.ReadAllLines(objOpenFile.FileName, Encoding.Default);


                foreach (string item in ReadText)
                {
                    if (item.ToUpper().Contains("ZZZ"))//搜索指定字符串ZZZ
                    {
                        ZZZString.Add(item);//搜索到的内容存入ZzzString集合
                        //richTextBox1.Text += item.ToString() + "\r\n";//添加一个richTextBox,把//去掉可看见搜索结果
                        //label1.Text = ZzzString.Count + "条";//添加一个label,把//去掉可看见数据总条数
                    }
                }
            }
        }
    }
}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值