Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

File-Text Replacement Tool

3.59/5 (4 votes)
22 Nov 2006CPOL2 min read 1   181  
A utility that substitutes file names from a file collection into a text template.

Sample Image - screen1.jpg

Introduction

The File-Text Replacement utility is a Windows application that substitutes file names from a file collection into a text template/snippet, and then generates a block of the template for every file encountered in the iteration/generation process.

Background

A few months ago, I had to create some ASP.NET pages and corresponding code that referred to several hundred images in a directory tree. Needless to say, I did not want to spend hours doing tedious HTML work to build these pages and references, so I created this utility to do most of the work for me (as any decent developer would!). Since then, I've found additional uses for this utility that has saved additional hours in coding and scripting work, such as in SQL statements, code snippets, and scripting blocks.

Using the Application

The File-Text Replacement tool is very simple to use - just point to the directory where you want to begin iterating files from, and then enter a text template that will be used in the file-text generation. Wherever you want a filename to appear in the text block, just specify a "[FILE]" tag, and during the generation process, this tag will be replaced with the file name.

You can also specify whether to iterate over all the subdirectories under the main folder, and also if you want to specify the relative paths to the files as they are enumerated. These are the "Recurse Sub-directories" and the "Include Relative Path" checkboxes, respectively.

Several other useful features are included, such as the standard Copy-Paste-SelectAll, which perform their actions on the active tab-textbox. Templates and generated text can be loaded and saved by the "Open File" and the "Save File" buttons, which also are dependent upon whichever tab-textbox is currently active.

A sample template

Template

Results of the file-replacement generation

Generated

The File-Text Replacement Engine - How it Works

The main engine/processor of the File-Text Replacement tool is actually quite simple. From the file collection specified by the root directory, for every file encountered in the iteration process, the file name or the relative file path is substituted for every "[FILE]" tag in the template. A collection of these substitutions is maintained during the iteration over the file collection, and then finally, it dumps the string collection into the Generated output textbox.

C#
private const string FILE_TAG = "[FILE]";
private const string FILENAME_TAG = "[NAME]";
private const string FILE_FILTER = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

private bool m_bIncludeRelativePath = false;
private bool m_bRecurseSubDirs = false;        

private string m_sFilePath = string.Empty;
private string m_sSourcePath = string.Empty;
private string m_sInputTemplate = string.Empty; 
...
...
...
/// <SUMMARY>
/// Generates the file-text contents based upon the template provided
/// </SUMMARY>
private void GenerateContents()
{
    txtGenerated.Text = string.Empty;
    GetProperties();

    try
    {
        StringBuilder sbContents = new StringBuilder();
        Cursor.Current = Cursors.WaitCursor;

        string[] sFiles = Directory.GetFiles(m_sSourcePath, "*", 
          (m_bRecurseSubDirs ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
        foreach (string sFile in sFiles)
        {
            FileInfo fiInfo = new FileInfo(sFile);
            string sGenerated = string.Empty;
            string sFileNameOnly = string.Empty;

            if (fiInfo.Extension.Trim() != string.Empty)
                sFileNameOnly = fiInfo.Name.Replace(fiInfo.Extension, string.Empty);
            else
                sFileNameOnly = fiInfo.Name;

            // replace for the filename-only (no ext)
            sGenerated = m_sInputTemplate.Replace(FILENAME_TAG, sFileNameOnly);

            // replace for the full-filename
            if (m_bIncludeRelativePath == true)
                sGenerated = sGenerated.Replace(FILE_TAG, 
                                 RelativePathTo(m_sSourcePath, sFile));
            else
                sGenerated = sGenerated.Replace(FILE_TAG, fiInfo.Name);

            sbContents.Append(sGenerated);
        }

        txtGenerated.Text = sbContents.ToString();
        txtGenerated.Select(0, 0);
    }
    catch (Exception ex)
    {
        MessageBox.Show("GenerateContents() Error: " + ex.Message, 
         "GenerateContents Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        Cursor.Current = Cursors.Default;
    }
}

/// <SUMMARY>
/// Updates the controls based upon the values of the private members
/// </SUMMARY>
private void SetProperties()
{
    chkIncludeRelativePath.Checked = m_bIncludeRelativePath;
    chkRecurseSubDirs.Checked = m_bRecurseSubDirs;

    txtSrcPath.Text = m_sSourcePath;
    txtTemplate.Text = m_sInputTemplate;
}

/// <SUMMARY>
/// Updates the private members based upon the control values
/// </SUMMARY>
private void GetProperties()
{
    m_bIncludeRelativePath = chkIncludeRelativePath.Checked;
    m_bRecurseSubDirs = chkRecurseSubDirs.Checked;

    m_sSourcePath = txtSrcPath.Text.Trim();
    m_sInputTemplate = txtTemplate.Text;
}

Conclusion

I hope you find this article and utility useful - it has come in quite handy a number of times, such as when generating HTML blocks, SQL statements, code snippets, and script blocks. Enjoy!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)