0

I have a open file dialog that open XML file. The regex expression find every string between > and <, and write every string in new line to the rich text box.

private void button1_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        StreamReader sr = new StreamReader(openFileDialog1.FileName);
        string s = sr.ReadToEnd();
        richTextBox1.Text = s;
    }

    string txt = richTextBox1.Text;
    var foundWords = Regex.Matches(txt, @"(?<=>)([\w ]+?)(?=<)");
    richTextBox1.Text = string.Join("\n", foundWords.Cast<Match>().Select(x => x.Value).ToArray());
}

Then I can change those strings. But how can I import those changed strings back to original XML file on its same place?

1 Answer 1

3

You could try to replace these strings inside a file, but once you replace something with a different length, it would be simpler to just write the entire file instead.

It looks like the user is able to modify these strings - that's your challenge there: you will have to keep track of which word was where in the original file to replace them back into the data. Furthermore the user is able to remove or add lines to the textbox, what would your application do in that case?

It would be easier to process the xml file using XDocument and store the XElements that contain the original values. XDocument allows you to replace these values and store the file.

Note that since you're not explicitly closing the StreamReader, the file may still be in use when you try to write it. Simply put the StreamReader in a using block to prevent this.

Sign up to request clarification or add additional context in comments.

5 Comments

But how can I rewrite whole file with new strings?
@orglce I'm suggesting that you modify the string in memory, and then write the whole file again. Once the user modifies these strings though there is no way to automatically put the modified versions back, so you'll need to somehow remember which string went where.
Maybe replace the RichTextBox with a DataGridView, defining two columns (first: original text, second: replacement), fill it with the found words, then after editing iterate over all rows in the datagrid and do the replacement as stated above.
@jCoder that sounds user-friendly, and each DataGridViewRow` could store the XElement in its Tag property when going for that approach.
@C.Evenhuis that would be neat, and depending on whether all occurrences of a text should be replaced or not, the text might be grouped in first column and a List<XElement> might be stored in the Tag

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.