Click here to Skip to main content
15,888,210 members
Articles / Programming Languages / C#

Regular Expression Filename Find and Replace

Rate me:
Please Sign up or sign in to vote.
4.86/5 (29 votes)
10 Feb 20072 min read 110.8K   2.3K   61  
Perform find and replace on file names with regular expressions.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

namespace RegexFilenames
{
    public partial class frmMain : Form
    {
        private bool dirty = false;
        private string projectPath = "";
        private string project = "New.rxproj";
        private bool projectNameSet = false;

        public frmMain()
        {
            InitializeComponent();
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            // create hte replace form
            frmReplace test = new frmReplace();

            // set options on the form
            test.Find = txtFind.Text;
            test.Replace = txtReplace.Text;
            test.TestOnly = true;
            test.SubDirectories = chkSubDirectories.Checked;
            test.Directory = txtDirectory.Text;

            // set the regex options
            if (chkCompiled.Checked)
                test.Options |= System.Text.RegularExpressions.RegexOptions.Compiled;

            if (chkIgnoreCase.Checked)
                test.Options |= System.Text.RegularExpressions.RegexOptions.IgnoreCase;

            if (chkIgnoreWS.Checked)
                test.Options |= System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace;

            // show the form
            test.Show();

            // do a trial run through the replacements
            test.ReplaceFiles();
        }

        private void btnReplace_Click(object sender, EventArgs e)
        {
            // replace the files
            if (MessageBox.Show("Are you sure you want to run this regex?\r\nThis cannot be undone!", "Are you sure?",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                // create the replace form
                frmReplace replace = new frmReplace();

                // set options on the form
                replace.Find = txtFind.Text;
                replace.Replace = txtReplace.Text;
                replace.TestOnly = false;
                replace.SubDirectories = chkSubDirectories.Checked;
                replace.Directory = txtDirectory.Text;

                // set the regex options
                if (chkCompiled.Checked)
                    replace.Options |= System.Text.RegularExpressions.RegexOptions.Compiled;

                if (chkIgnoreCase.Checked)
                    replace.Options |= System.Text.RegularExpressions.RegexOptions.IgnoreCase;

                if (chkIgnoreWS.Checked)
                    replace.Options |= System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace;

                // show the form that does the replacements 
                replace.Show();

                // replace the files
                replace.ReplaceFiles();
            }
        }

        private void btnFindDirectory_Click(object sender, EventArgs e)
        {
            // popup a box to find the directory. Using a file open dialog because the
            // directory find dialog is screwed up on XP SP2
            if (dlgOpen.ShowDialog() == DialogResult.OK)
            {
                txtDirectory.Text = Path.GetDirectoryName(dlgOpen.FileName);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // exit the program.
            this.Close();

            Application.Exit();
        }

        private void newProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // clear out all the text fields
            txtDirectory.Text = "";
            txtFind.Text = "";
            txtReplace.Text = "";

            // reset the checkboxes
            chkCompiled.Checked = true;
            chkIgnoreCase.Checked = true;
            chkIgnoreWS.Checked = true;
            chkSubDirectories.Checked = false;

            // update the project details
            dirty = false;
            projectNameSet = false;
            projectPath = "";
            project = "New.rxproj";
            this.Text = "Rexeg Find and Replace File Names - " + project;
        }

        private void openProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // check if the current project needs to be saved before we continue
            if (dirty)
            {
                // yes, give them the option to save
                if (MessageBox.Show("Do you wish to save your current project first?", "Save first?",
                    MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    // run the save method
                    saveProjectToolStripMenuItem_Click(sender, e);
                }
            }

            // find a project to open
            if (dlgOpenProject.ShowDialog() == DialogResult.OK)
            {
                // load the xml file in
                XmlDocument doc = new XmlDocument();
                doc.Load(dlgOpenProject.FileName);

                // check to see if its valid
                if (doc.DocumentElement.Name != "rxproject")
                {
                    // not valid, we can't continue
                    MessageBox.Show("Not a valid project file", "Invalid Project", 
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                // load in the text boxes and their data
                txtDirectory.Text = doc.SelectSingleNode("/rxproject/directory").InnerText;
                txtFind.Text = doc.SelectSingleNode("/rxproject/find").InnerText;
                txtReplace.Text = doc.SelectSingleNode("/rxproject/replace").InnerText;

                // load in the check boxes and their states
                chkCompiled.Checked = Boolean.Parse(doc.SelectSingleNode("/rxproject/compiled").InnerText);
                chkIgnoreCase.Checked = Boolean.Parse(doc.SelectSingleNode("/rxproject/ignorecase").InnerText);
                chkIgnoreWS.Checked = Boolean.Parse(doc.SelectSingleNode("/rxproject/ignorews").InnerText);
                chkSubDirectories.Checked = Boolean.Parse(doc.SelectSingleNode("/rxproject/subdirectories").InnerText);

                // set project details, and update the window title
                dirty = false;
                project = Path.GetFileName(dlgOpenProject.FileName);
                projectPath = dlgOpenProject.FileName;
                projectNameSet = true;
                this.Text = "Rexeg Find and Replace File Names - " + project;
            }
        }

        private void saveProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // check if we have a project path already set
            if (!projectNameSet)
            {
                // no.. find somewhere to save tihs
                if (dlgSaveProject.ShowDialog() == DialogResult.OK)
                {
                    projectPath = dlgSaveProject.FileName;
                    project = Path.GetFileName(dlgSaveProject.FileName);
                    projectNameSet = true;
                }
                else
                {
                    return;
                }
            }

            // create a document to contain the data in
            XmlDocument doc = new XmlDocument();
            
            // root node
            XmlNode node = doc.CreateNode(XmlNodeType.Element, "rxproject", "");
            doc.AppendChild(node);

            // text fields
            node = doc.CreateNode(XmlNodeType.Element, "directory", "");
            node.InnerText = txtDirectory.Text;
            doc.DocumentElement.AppendChild(node);

            node = doc.CreateNode(XmlNodeType.Element, "find", "");
            node.InnerText = txtFind.Text;
            doc.DocumentElement.AppendChild(node);

            node = doc.CreateNode(XmlNodeType.Element, "replace", "");
            node.InnerText = txtReplace.Text;
            doc.DocumentElement.AppendChild(node);

            // check boxes
            node = doc.CreateNode(XmlNodeType.Element, "compiled", "");
            node.InnerText = chkCompiled.Checked.ToString();
            doc.DocumentElement.AppendChild(node);

            node = doc.CreateNode(XmlNodeType.Element, "ignorecase", "");
            node.InnerText = chkIgnoreCase.Checked.ToString();
            doc.DocumentElement.AppendChild(node);

            node = doc.CreateNode(XmlNodeType.Element, "ignorews", "");
            node.InnerText = chkIgnoreWS.Checked.ToString();
            doc.DocumentElement.AppendChild(node);

            node = doc.CreateNode(XmlNodeType.Element, "subdirectories", "");
            node.InnerText = chkSubDirectories.Checked.ToString();
            doc.DocumentElement.AppendChild(node);

            // save it away
            doc.Save(projectPath);

            // no longer dirty - update window title
            dirty = false;
            //project = Path.GetFileName(projectPath);
            this.Text = "Rexeg Find and Replace File Names - " + project;
        }

        private void evntTextChanged(object sender, EventArgs e)
        {
            // a field on the form was changed. make it dirty.
            dirty = true;

            this.Text = "Rexeg Find and Replace File Names - " + project + "*";
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            // check if the current project needs to be saved before we continue
            if (dirty)
            {
                // yes, give them the option to save
                if (MessageBox.Show("Do you wish to save your current project first?", "Save first?",
                    MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    // run the save method
                    saveProjectToolStripMenuItem_Click(sender, e);
                }
            }
        }

        private void PaintPanel(object sender, PaintEventArgs e)
        {
            // this wouldnt work if the form was able to be resized. lucky it cant be :)
            using (Pen p = new Pen(SystemBrushes.ControlDark))
            {
                Control c = (Control)sender;
                e.Graphics.DrawRectangle(p, new Rectangle(1, 1, c.Width - 2, c.Height - 2));
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer
Australia Australia
Mark spends his spare time working on his radio control planes, helicopters and trucks. He devises new ways to make them crash faster and easier than ever before. Mark has progressed this joy of destroying nice toys into build UAV's - which can crash themselves with, or without user input.

Mark enjoys all aspects of C#, specifically windows programming and regular expressions.

Comments and Discussions