以特定值和行写入文件

本文关键字:文件 | 更新日期: 2023-09-27 18:37:01

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

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

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 返回错误。这是读取线部分代码:

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

以特定值和行写入文件

请尝试将 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);