C# key取value

条件:C#

       有一个txt文档,内容如下-

张一=3001
张二=3002
张三=3003
张四=3004
……

 

 

1。将其内容读到程序中

 if (File.Exists(@"/My Documents/rec.txt"))//文件rec.txt存在时候才读取
                {
                    StreamReader sr = null;
                    try
                    {
                        sr = new StreamReader(@"/My Documents/rec.txt", Encoding.Unicode, false);
                        while (sr.Peek() >= 0)  //一直读到文件尾
                        {
                            string[] s = r.Split(sr.ReadLine());
                            if (s.Length >= 2){
                                ht.Add(s[1].Trim(), s[0].Trim());      //使用hashtable存储,ht(key,value)

                                                                                       //“3001”作为key,“张一”作为value
                            }
                        }
                    }
                    finally
                    {
                        sr.Close();
                    }

 

2。根据key取value

     key由页面控件取得

     string key = this.text1.text.tostring().trim()

     if (ht.ContainsKey(key))
        value= ht[key].ToString();

如 :key=“3002”,则 value = “张二”

 

3。导出数据到txt

            FileStream fsout = null;
            StreamWriter swout = null;
            try
            {
                fsout = new FileStream(@"/My Documents/报告.txt", FileMode.Create);
                swout = new StreamWriter(fsout, Encoding.Unicode);

                for (int i = 0; i < this.ListView1_EPC.Items.Count; i++)
                {
                    swout.WriteLine(this.ListView1_EPC.Items[i].SubItems[1].Text.ToString());
                 }
                swout.Flush();
                MessageBox.Show("保存成功!");
            }
            finally
            {
                swout.Close();
                fsout.Close();
            }

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值