18
2012
05

C# 下查询某个文件夹下面所有文本文件的内容或文件名

        private void btnSearch_Click(object sender, EventArgs e)   //点击按钮
        {
            if (txtTitle.Text.Trim() != "")   //要查询的条件文本框
            {
                DataTable datatable = SearchFile(comboBox1, txtTitle.Text.Trim());   //查询文本内容
                dataGridView1.DataSource = datatable;    //绑定dataGridView
            }
            else
            {
                MessageBox.Show("请输入要查询的内容!");
            }
        }

        private DataTable SearchFile(ComboBox comboBox, string Txt)
        {
            DataTable db = new DataTable();
            db.Columns.Add("ID", System.Type.GetType("System.String"));   //创建一个列
            db.Columns.Add("Name", System.Type.GetType("System.String"));  //创建一个列
            string Path = Application.StartupPath + @"\File";   //项目下的bin里面的File文件夹
            //在指定目录及子目录下查找文件,在listBox1中列出子目录及文件
            DirectoryInfo Dir = new DirectoryInfo(Path);  
            try
            {
                int i = 1;
                comboBox.Items.Clear();
                foreach (FileInfo f in Dir.GetFiles("*.txt"))             //查找文件
                {
                    if (SearchData(f, Txt) || f.ToString().IndexOf(Txt) != -1)   //判断文件夹名和文件内容是否含有内容
                    {
                        DataRow newdr = db.NewRow();
                        comboBox.Items.Add(f.ToString());     //向ComboBox中填加文件名
                        newdr[0] = i;
                        newdr[1] = f.ToString();
                        db.Rows.Add(newdr);
                        i++;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
            }
            return db;
        }

        public bool SearchData(FileInfo file, string Txt)
        {
            string Path = Application.StartupPath + @"\File" + "\\" + file;
            txtPath.Text = Path.ToString();
            Encoding fileEncoding = GetEncoding(Path);    //开始读取文本内容

            StreamReader sr = new StreamReader(Path, fileEncoding);     //用该编码创建StreamReader
            string strLine = sr.ReadLine();    //读取文件中的一行

            while (strLine != null)//判断是否为空,表示到文件最后一行了
            {
                if (strLine.IndexOf(Txt) != -1)   //判断某一行是否存在某字符串,存在就说明该文件包含内容,返回true
                {
                    sr.Close();
                    return true;
                }
                strLine = sr.ReadLine();
            }
            //关闭文件,注意顺序,先对文件内部进行关闭,然后才是文件~
            sr.Close();
            return false;
        }

« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。