以特定值和行写入文件

时间:2013-10-26 14:51:44

标签: c# .net winforms file text

我想从文本框中以文本文件中的指定值写入数据。这是一个例子:

item_begin etcitem 3344 item_type=etcitem是第一行,item_begin weapon 3343 item_type=weapon是第二行。好吧,我想用item_type=weapon替换第二行的item_type=armor。到目前为止,这是代码:

var data2 = File.WriteAllLines("itemdata.txt")
    .Where(x => x.Contains("3343"))
    .Take(1)
    .SelectMany(x => x.Split('\t'))
    .Select(x => x.Split('='))
    .Where(x => x.Length > 1)
    .ToDictionary(x => x[0].Trim(), x => x[1]);

但是WriteAllLines返回错误。 这是readline部分代码:

var data = File.ReadLines("itemdata.txt")
    .Where(x => x.Contains("3343"))
    .Take(1)
    .SelectMany(x => x.Split('\t'))
    .Select(x => x.Split('='))
    .Where(x => x.Length > 1)
    .ToDictionary(x => x[0].Trim(), x => x[1]);
//call values

textitem_type.Text = data["item_type"];

并希望在阅读后写出我在textitem_type.Text上更改的相同值。

我用它来重新加载,但是用line替换所有具有相同名称的值,并在文本中仅返回1行。代码:

 private void button2_Click(object sender, EventArgs e)
    {
        var data = File
                    .ReadLines("itemdata.txt")
                    .Where(x => x.Contains(itemSrchtxt.Text))
                    .Take(1)
                    .SelectMany(x => x.Split('\t'))
                    .Select(x => x.Split('='))
                    .Where(x => x.Length > 1)
                    .ToDictionary(x => x[0].Trim(), x => x[1]);
        StreamReader reader = new StreamReader(Directory.GetCurrentDirectory() + @"\itemdata.txt");
        string content = reader.ReadLine();
        reader.Close();
        content = Regex.Replace(content, data["item_type"], textitem_type.Text);
          StreamWriter write = new StreamWriter(Directory.GetCurrentDirectory() + @"\itemdata.txt");
        write.WriteLine(content);
        write.Close();
    }

1 个答案:

答案 0 :(得分:0)

请尝试将 WriteAllLines 替换为 ReadAllLines

var data2 = File.ReadAllLines("itemdata.txt");

//use linq if you want, it just an example fo understandin
Foreach (var dataline in data2 ) 
{
   if (dataline.Contains("3343"))
       dataline = "item_begin weapon 3343 item_type=weapon" //of course you can use the split, it just an example
}

File.WriteAllLines("itemdata.txt", data2);