DanF
DanF

Reputation: 115

Search and Replace string in file in C#

I am trying to create a small form in C# to find one string in a TMX file (xml) and replace it for another. Then it would create an output file with all the modifications. The form contains a search button to locate the file in the local disk and a REPLACE button which it would change "srclang="all"" for "srclang="en-US"". So far I have the following:

    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        using (FileDialog fileDialog = new OpenFileDialog())
        {
            if (DialogResult.OK == fileDialog.ShowDialog())
            {
                string filename = fileDialog.FileName;

                textBox1.Text = fileDialog.FileName;
            }
        }
    }

    private void label1_Click(object sender, EventArgs e)
    {

    }

    private void button3_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void button2_Click(object sender, EventArgs e)
    {
       StreamWriter writer = null;
        Dictionary<string, string> replacements = new Dictionary<string, string>();
        replacements.Add("*all*", "en-US");
        // ... further replacement entries ...

        using (writer = File.CreateText("output.txt"))
        {
            foreach (string line in File.ReadLines(textBox1.Text))
            {
                bool replacementMade = false;
                foreach (var replacement in replacements)
                {
                    if (line.StartsWith(replacement.Key))
                    {
                        writer.WriteLine(string.Format("{1}",
                            replacement.Key, replacement.Value));
                        replacementMade = true;
                        break;
                    }
                }
                if (!replacementMade)
                {
                    writer.WriteLine(line);
                }
            }
        }

        File.Replace("output.txt", textBox1.Text, "ORIGINAL_TMX_FILE.bak");
    }
    }
}

This code is from Dave R. from this site, it really works with TXT files but I am not sure what I am doing wrong. I am totally a newbie here. If anyone could help me write some lines to make it work, I would really appreciate it!

Upvotes: 0

Views: 736

Answers (2)

Kit
Kit

Reputation: 21739

Probably the simplest thing that could work would be to use these methods

as in the example below:

File.WriteAllLines(
    outputFileName,
    File.ReadAllLines(inputFileName)
        .Select(line => line.Replace(@"srclang=""en-US""", @"srclang=""all"""));

If there could be whitespace in the search text, you could replace the call to string.Replace with a Regex.Replace.

Upvotes: 1

selator
selator

Reputation: 76

I think I understand what you're trying to do and the following segment is the essence of your code:

if (line.StartsWith(replacement.Key))
    {
        writer.WriteLine(string.Format("{1}",
            replacement.Key, replacement.Value));
        replacementMade = true;
        break;
    }

If your dictionary will always have one element, you only have to change the parameter of the WriteLine call. You're writing only the replacement value instead of the whole line with the replacements done on it. You might want to have something like

writer.WriteLine(line.Replace(replacement.Key, replacement.Value)

If you want to check for several replacements, store the replaced line in the inner loop and only write it at the end and remove the break command.

Another unrelated observation: the replacement.Key parameter in the WriteLine call is omitted since {1} refers to the second additional parameter (counting starts from 0).

Upvotes: 1

Related Questions