Write file at a specific value and line
Posted
by
user2828891
on Stack Overflow
See other posts from Stack Overflow
or by user2828891
Published on 2013-10-26T14:51:43Z
Indexed on
2013/10/26
15:54 UTC
Read the original article
Hit count: 205
I want to write data at a specified value in a text file from a text box. Here is a example:
item_begin etcitem 3344 item_type=etcitem
is first line and item_begin weapon 3343 item_type=weapon
is second. Well i want to replace item_type=weapon
at second line with item_type=armor
. Here is code so far:
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]);
But returns error at WriteAllLines. Here is the readline part code:
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"];
And want to write the same value I change on textitem_type.Text
after read.
I used this to reaplace but replaces all values with same name from line and returns me in text only 1 line. Code:
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();
}
© Stack Overflow or respective owner