积极答复者
关于读取键值对

问题
-
大家好. 新手请教,我现在手上有一个txt的文本 内容大致如下:
***********txt***********
myname=picasso
hisname=san.zhang
hername=si.li
...
...
***********txt***********
我想把它读取出来 然后 实例化一个SortedDictionary 用 KeyValuePair 将 [myname,picasso][hisname,san.zhang] 等 以一个键值对的形式存放到已经实例化的SortedDictionary中.
请问有高手能给出具体点的代码吗? 方法不限 只要最后能存到 已经实例化的SortedDictionary中就好。
答案
-
private void LoadDataFromFile(string filename, ref System.Collections.Generic.SortedList<string, string> list) { if(null == list || string.IsNullOrEmpty(filename)) return; System.IO.FileStream fs = new FileStream(filename,FileMode.Open, FileAccess.Read); System.IO.TextReader reader = new System.IO.StreamReader(fs); string line = null; string[] items = null; while(null != (line = reader.ReadLine())) { items = line.Split(new char[]{'='}); if(2 != items.Length) continue; list.Add(items[0], items[1]); } reader.Close(); fs.Close(); }
调用:
System.Collections.Generic.SortedList<string, string> list = new System.Collections.Generic.SortedList<string, string>(); LoadDataFromFile("F:\\aa.txt", ref list); foreach (KeyValuePair<string, string> item in list) { // output data..... }
- 已标记为答案 Picasso Huang 2010年2月12日 5:24
全部回复
-
private void LoadDataFromFile(string filename, ref System.Collections.Generic.SortedList<string, string> list) { if(null == list || string.IsNullOrEmpty(filename)) return; System.IO.FileStream fs = new FileStream(filename,FileMode.Open, FileAccess.Read); System.IO.TextReader reader = new System.IO.StreamReader(fs); string line = null; string[] items = null; while(null != (line = reader.ReadLine())) { items = line.Split(new char[]{'='}); if(2 != items.Length) continue; list.Add(items[0], items[1]); } reader.Close(); fs.Close(); }
调用:
System.Collections.Generic.SortedList<string, string> list = new System.Collections.Generic.SortedList<string, string>(); LoadDataFromFile("F:\\aa.txt", ref list); foreach (KeyValuePair<string, string> item in list) { // output data..... }
- 已标记为答案 Picasso Huang 2010年2月12日 5:24