C # Replace String parts in txt file

0

Hello.

I'm studying C # and I'm having trouble with a function.

I have an array, as below, where each node contains an id, a pattern (regex) and a value to replace the part of the string that matches that value.

I load the contents of the txt file into contenFile and if, for example, it matches some part of the content, the match is replaced with "ABC" and so on with the rest of the array. If it does not match, enter the value at the end.

The file contains fields to match and not match

< tag 101 >       < tag2 > BBBBBBBBBBB < / tag2 >       < tag4 > CCCCCCCC < / tag4 > < tag 101 ">

If anyone can help or indicate content for study, thank you.

At the moment the code looks like this:

public void Edit()
{
string[,] items = {{"001", "<tag ([0-9]{3})\">", "ABC"},
                    {"002", "<tag2>.+</tag2>", "DEF"},
                    {"", "<tag3>.+</tag3>", "GHI"}};
try
{
using (StreamReader sr = new StreamReader(@"C:\test.xml"))
{
string contentFile = sr.ReadToEnd();

foreach (string entry in items)
{
if (!Regex.IsMatch(contentFile, entry[1].ToString()))
{
contentFile = contentFile.Insert(contentFile.Length, entry[2].ToString());
}
else
{
contentFile = Regex.Replace(contentFile, entry[1].ToString(), entry[2].ToString());
}
}
}
}
catch (Exception ex)
{
}
}
    
asked by anonymous 01.05.2018 / 03:45

0 answers