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