C#如何读取文件前面说过了:http://blog.csdn.net/yysyangyangyangshan/article/details/6948327,下面以一个例子来说明如何按行读取,其实很简单,就是使用FileStream的ReadLine()方法。
例如有这样一个文件test.txt,读取出来显示在一个richtextbox中,文件内容如下:
例如有这样一个文件test.txt,读取出来显示在一个richtextbox中,文件内容如下:
诺基亚 =N8
摩托罗拉 =ME525+
华为 =HONOR
HTC=A3366/T9299
读取方法为:
public static Dictionary<string, string> ReadLineFile()
{
string filePath = Common.StartupPath + @"test.txt";
Dictionary<string, string> contentDictionary = new Dictionary<string, string>();
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如图:
详细工程:http://download.csdn.net/detail/yysyangyangyangshan/4073781