C#如何读取文件前面说过了:,下面以一个例子来说明如何按行读取,其实很简单,就是使用FileStream的ReadLine()方法。
例如有这样一个文件,读取出来显示在一个richtextbox中,文件内容如下:
诺基亚 =N8 摩托罗拉 =ME525+ 华为 =HONOR HTC=A3366/T9299读取方法为:
public static Dictionary ReadLineFile() { string filePath = Common.StartupPath + @"; Dictionary contentDictionary = new Dictionary(); if (!File.Exists(filePath)) { return contentDictionary; } FileStream fileStream = null; StreamReader streamReader = null; try { fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); streamReader = new StreamReader(fileStream, Encoding.Default); fileStream.Seek(0, SeekOrigin.Begin); string content = streamReader.ReadLine(); while (content != null) { if (content.Contains("=")) { string key = content.Substring(0, content.LastIndexOf("=")).Trim(); string value = content.Substring(content.LastIndexOf("=") + 1).Trim(); if (!contentDictionary.ContainsKey(key)) { contentDictionary.Add(key, value); } } content = streamReader.ReadLine(); } } catch { } finally { if (fileStream != null) { fileStream.Close(); } if (streamReader != null) { streamReader.Close(); } } return contentDictionary; }
显示richtextbox如图:
本文发布于:2024-02-01 03:40:49,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170673005133597.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |