C#哈希表数据与文本数据转换

本文介绍了一个用于将文本文件转换为哈希表的公共方法,并提供了一个反向操作的方法,即将哈希表的内容写回到文本文件中。这些方法可用于简单的数据持久化场景。

 

 

public Hashtable txt2hash(FileInfo file)
    {
        StreamReader sr = new StreamReader(file.FullName, Encoding.UTF8);
        Hashtable ht = new Hashtable();
        int k = 0;
        string nextline = sr.ReadLine();
        while (nextline != null)
        {
          
            k = nextline.IndexOf("&", 0);//&是键和值的分隔符
            string key1 = nextline.Substring(0, k).ToString();
            string value1 = nextline.Substring(k + 1, nextline.Length - k - 1).ToString();
            if (!ht.Contains(key1))
            {
                ht.Add(key1, value1);
              
 
            }
            nextline = sr.ReadLine();
           
        }

        sr.Close();
        return ht;

 

//IDictionaryEnumerator de = ht.GetEnumerator();//测试输出
   //     while (de.MoveNext())
     //   {
   //         Response.Write(de.Key.ToString()+de.Value.ToString()+"<br>");
  //      }
 

    }

 

public void hash2txt(Hashtable ht)
    {
        Random r = new Random();//随机产生文件名保存成txt文件

        string name = r.Next(1000).ToString();
        FileInfo myfile = new FileInfo(Server.MapPath("~/index/" + name + ".txt"));
        StreamWriter sw = myfile.CreateText();

        IDictionaryEnumerator de = ht.GetEnumerator();
        while (de.MoveNext())
        {
            sw.WriteLine(de.Key.ToString() + "&" + de.Value.ToString());

        }
        sw.Close();
    }

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值