Reputation: 21
I want to replace a specific text at in a line at a specific part. Example text:
begin 355 weapon item_type=weapon
begin 356 armor item_type=armor
I want to replace item_type=weapon
to item_type=none
at line 1 by value 355
from it without replacing all weapon
text from it and to not clean all lines and replace all with 1 line. Here is my code so far:
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();
}
Here is the real line I use:
item_begin questitem 783 [_alankells_receipt] item_type=questitem
Upvotes: 0
Views: 138
Reputation: 3681
This isn't in LINQ but LINQ looks like overkill for what you want:
var lines = File.ReadAllLines(Directory.GetCurrentDirectory() + @"\itemdata.txt");
if (lines.Length > 0)
{
var fields = lines[0].Split('\t');
if (fields.Length >= 4 && fields[1] == "355" && fields[3] == "item_type=weapon")
fields[3] = "item_type=none";
lines[0] = string.Join("\t", fields);
}
File.WriteAllLines(Directory.GetCurrentDirectory() + @"\itemdata.txt", lines);
Create a file called C:\temp\t.txt
. Open it in Notepad and paste this in:
begin 355 weapon item_type=weapon
begin 356 armor item_type=armor
Make sure there is a tab (\t
) and not a space between 355 and weapon and same on the second line between 356 and armor (the tab is coming out as a space when I copy-paste). Save the file and close Notepad.
Run this code (I use LinqPad):
var lines = File.ReadAllLines(@"C:\temp\t.txt");
if (lines.Length > 0)
{
var fields = lines[0].Split('\t');
if (fields.Length >= 4 && fields[1] == "355" && fields[3] == "item_type=weapon")
fields[3] = "item_type=none";
lines[0] = string.Join("\t", fields);
}
File.WriteAllLines(@"C:\temp\t.txt", lines);
Open the file again in Notepad.
Upvotes: 2