按行读取TXT文件中的内容

  

 1 public Dictionary<int, string> GetDicFromLog()
 2         {
 3             try
 4             {
 5                 StreamReader sr = new StreamReader(fileName, Encoding.Default);
 6                 string line;
 7                 Dictionary<int, string> dic = new Dictionary<int, string>();
 8                 int i = 0;
 9                 while ((line = sr.ReadLine()) != null)
10                 {
11                     i++;
12                     dic.Add(i, line);
13                 }
14                 return dic;
15             }
16             catch (Exception ex)
17             {
18 
19                 throw;
20             }
21         }

  关键在于StreamReader类和ReadLine方法的使用(引用的是System.IO)。

  fileName表示TXT文件的路径。

  这里根据需要,将从TXT文件中读取的内容添加至Dictionary集合中,TXT文件的行号作为Dictionary集合的key值。

原文地址:https://www.cnblogs.com/yupeiyuan/p/5212680.html