C#编程-读写文本

本文介绍了一种从文本文件中读取并解析数据的方法,包括打开文件、逐行读取内容、处理注释行及空白行,并提取特定格式的关键信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于文本文件进行读取,通过解析文本文件,来获得相应数据。

        /// <summary>
        /// 解析文本文件,根据文本文件来获取所需要的数据
        /// </summary>
        /// <param name="FileName">文件名</param>
        /// <returns>文件正确,返回为true,错误返回为false</returns>
        private bool ReadFile(string FileName)
        {
            //参数定义
            FileStream fs = null;
            StreamReader sr = null;
            //每行字符串
            string StrLine;
            //行数
            int LineCount = 0;
            //文本中一共多少个字符
            int StrCharCount = 0;
            //定义其他参数
            try
            {
                if (FileName == null || !File.Exists(FileName))
                {
                    return false;
                }
                fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
                sr = new StreamReader(fs);  //使用StreamReader类来读取文件 
                sr.BaseStream.Seek(0, SeekOrigin.Begin);
                while ((StrLine = sr.ReadLine()) != null)
                {
                    LineCount++;
                    StrLine = StrLine.Trim();
                    if (StrLine == "" || StrLine.IndexOf("//") >= 0)
                    {
                        continue;
                    }
                    StrCharCount = StrLine.Length;
                    //根据标志符来提取关键字
                    if (StrLine.IndexOf("Flag=") >= 0)
                    {
                        StrLine.Substring("Flag=".Length, StrCharCount - "Flag=".Length);
                    }
                }
                return true;
            }
            catch 
            {
                return false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }

  

转载于:https://www.cnblogs.com/shumaojie/archive/2013/03/28/2986225.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值