C#编程-读写文本

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

        /// <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();
                }
            }
        }

  

posted @ 2013-03-28 10:45  竖毛杰  阅读(322)  评论(0编辑  收藏  举报