我想从文本框中以指定值写入文本文件中的数据。这是一个例子:
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();
}