Click here to Skip to main content
15,896,207 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 111.2K   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.Text.RegularExpressions;
using System.IO;

namespace RegexFilenames
{
    public partial class frmReplace : Form
    {
        public frmReplace()
        {
            InitializeComponent();
        }

        private RegexOptions options;
        public RegexOptions Options
        {
            get { return options; }
            set { options = value; }
        }

        private string find;
        public string Find
        {
            get { return find; }
            set { find = value; }
        }

        private string replace;
        public string Replace
        {
            get { return replace; }
            set { replace = value; }
        }

        private string directory;
        public string Directory
        {
            get { return directory; }
            set { directory = value; }
        }

        private bool subDirectories;
        public bool SubDirectories
        {
            get { return subDirectories; }
            set { subDirectories = value; }
        }

        private bool testOnly;
        public bool TestOnly
        {
            get { return testOnly; }
            set { testOnly = value; }
        }

        /// <summary>
        /// Replace files on the disk based on properties set on this form.
        /// </summary>
        public void ReplaceFiles()
        {
            // create the regex object
            Regex rex = new Regex(find, options);

            // work out if we are going to be searching sub directories
            SearchOption searchOption = SearchOption.TopDirectoryOnly;
            if (subDirectories)
            {
                searchOption = SearchOption.AllDirectories;
            }

            // find files within the directory
            string[] files = System.IO.Directory.GetFiles(directory, "*.*", searchOption);

            // setup the progress bar
            pbReplace.Maximum = files.Length;

            // iterator for the progress bar
            int i = 0;
            
            // stop painting of the list
            lstReplacements.BeginUpdate();
           
            // process each file
            foreach (string file in files)
            {
                // move the progress bar along
                pbReplace.Value = ++i;

                // find just the file name.. no need to replace anything in the path
                string name = Path.GetFileName(file);

                // does it match the expression?
                if (rex.IsMatch(name))
                {
                    // find out the new name after replacement
                    string newName = rex.Replace(name, replace);

                    // the path that this came from
                    string path = Path.GetDirectoryName(file);

                    // add an item to the list showing the replacement
                    lstReplacements.Items.Add(
                        path + Path.DirectorySeparatorChar + name + " -> " + 
                        path + Path.DirectorySeparatorChar + newName);

                    // don't rename the file if this is only a test run
                    if (!testOnly)
                    {
                        // rename the file
                        File.Move(path + Path.DirectorySeparatorChar + name, 
                            path + Path.DirectorySeparatorChar + newName);
                    }
                }
            }
            // resume painting
            lstReplacements.EndUpdate();
        }
    }
}

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