0

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

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读后改变的相同值。

我用它来重新放置,但替换了所有具有相同名称的值,并在文本中仅返回 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();
    }
4

1 回答 1

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);
于 2013-10-26T14:56:01.707 回答