C#读取文件:按行读取

zz:  http://blog.csdn.net/yysyangyangyangshan/article/details/7272611#comments


C#如何读取文件前面说过了:http://blog.csdn.net/yysyangyangyangshan/article/details/6948327,下面以一个例子来说明如何按行读取,其实很简单,就是使用FileStream的ReadLine()方法。
例如有这样一个文件test.txt,读取出来显示在一个richtextbox中,文件内容如下:

[html]  view plain copy print ?
  1. 诺基亚    =N8  
  2. 摩托罗拉  =ME525+  
  3. 华为   =HONOR  
  4. HTC=A3366/T9299  
读取方法为:
[csharp]  view plain copy print ?
  1. public static Dictionary<stringstring> ReadLineFile()  
  2.        {  
  3.            string filePath = Common.StartupPath + @"test.txt";  
  4.   
  5.            Dictionary<stringstring> contentDictionary = new Dictionary<stringstring>();  
  6.   
  7.            if (!File.Exists(filePath))  
  8.            {  
  9.                return contentDictionary;  
  10.            }  
  11.   
  12.            FileStream fileStream = null;  
  13.   
  14.            StreamReader streamReader = null;  
  15.   
  16.            try  
  17.            {  
  18.                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);  
  19.   
  20.                streamReader = new StreamReader(fileStream, Encoding.Default);  
  21.   
  22.                fileStream.Seek(0, SeekOrigin.Begin);  
  23.   
  24.                string content = streamReader.ReadLine();  
  25.   
  26.                while (content != null)  
  27.                {  
  28.                    if (content.Contains("="))  
  29.                    {  
  30.                        string key = content.Substring(0, content.LastIndexOf("=")).Trim();  
  31.   
  32.                        string value = content.Substring(content.LastIndexOf("=") + 1).Trim();  
  33.   
  34.                        if (!contentDictionary.ContainsKey(key))  
  35.                        {  
  36.                            contentDictionary.Add(key, value);  
  37.                        }  
  38.                    }  
  39.                    content = streamReader.ReadLine();  
  40.                }  
  41.            }  
  42.            catch  
  43.            {  
  44.            }  
  45.            finally  
  46.            {  
  47.                if (fileStream != null)  
  48.                {  
  49.                    fileStream.Close();  
  50.                }  
  51.                if (streamReader != null)  
  52.                {  
  53.                    streamReader.Close();  
  54.                }  
  55.            }  
  56.            return contentDictionary;  
  57.        }  

显示richtextbox如图:


详细工程:http://download.csdn.net/detail/yysyangyangyangshan/4073781



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值