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();
    }

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值