winform对TXT文本文件的操作

//=====================
//描述:读取TXT文件
//本例中向一个ListBox添加信息
//ListBox的名字为TxtListBox
//
//返回:void
//作者:Kunsa
//创建时间:2010.5.4
//状态:已完成
//修改:
//=====================
private void TxtRead(string filename)
{
    FileStream fs = new FileStream(filename,FileMode.Open,FileAccess.Read);
    StreamReader sr = new StreamReader(fs);
    sr.BaseStream.Seek(0, SeekOrigin.Begin);//从开始读取
    string str = sr.ReadLine();
    this.TxtListBox.Items.Clear();//清空ListBox中的内容
    while(str!=null)
    {
        this.TxtListBox.Items.Add(str);
        str = sr.ReadLine();
    }
    sr.Close();
    fs.Close();
}


//判断文本文件行数方法

        /// <summary>
        /// 获取文本文件的行数
        /// </summary>
        /// <param name="path">文本文件的路径</param>
        /// <returns>行数</returns>
        public int lineIndex(string path)
        {
            int Length = 0;
            StreamReader FileStreamTemp = new StreamReader(path);
            while ((FileStreamTemp.ReadLine()) != null)
            {
                Length++;
            }
            FileStreamTemp.Close();
            return Length;
        }

//逐行读取方法

        private void ReadTXTLineByLine()
        {
            string path = "";
            System.IO.StreamReader file = new System.IO.StreamReader(path);//创建文件流,path为文本文件路径
            int counter = 0;
            string line = "";
            string output = "";
            int lineLength = lineIndex(path);
            for (int _i = 0; _i < lineLength; _i++)
            {
                if ((line = file.ReadLine()) != null)
                {
                    output = line;
                    MessageBox.Show("第" + counter.ToString() + "行读取成功,内容:\n" + output);
                }

                if (_i == (lineLength - 1))
                {
                    MessageBox.Show("文本已读取完毕");
                }
            }
        }


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值