[Skip to Content]

Published Sunday 29 July 2018
Categories: General | Programming and Code |

Post View Counter 289

Code header

Over the past 2 months there has been a heatwave in the United Kingdom and so we haven’t been doing many electronics or new projects due to the high temperatures in the loft workshop.

We have been spending time working on our website projects and also on search engine optimisation for our own websites.

Part of this work has been to fix possible duplicate URL projects due to mixed case urls and internal page links to files or folders with upper and lower-case file name.

In the web.config files we are using URL Rewrite to set all requests to lower case, but this causes a 301 redirect for any files which have upper or mixed case file names or folder paths.

The web.config code to redirect to lower case urls is:

<rule enabled="true" name="rule" stopprocessing="true">
    <match url="(.*)">
            <add ignorecase="false" input="{URL}" pattern="[A-Z]">
    <action redirecttype="Permanent" type="Redirect" url="{ToLower:{URL}}">

With the website now requesting all lower-case files the next step is to rename any mixed or upper-case files in the site.

Rather than manually going through each folder and renaming the files, I wrote this short script which recursively scans a folder and lists all files which have mixed or upper-case names.

// Set root directory for files and folders to list
string[] files = Directory.GetFiles(Server.MapPath("/docs/"), "*.*", SearchOption.AllDirectories);

// Display all the files.
foreach (string file in files)
    string newfile = file.Replace("G:\\sites\\briandorey.com\\wwwroot\\", "");
    if (newfile.Any(char.IsUpper))
        Response.Write(newfile + "
        // Rename Files to lower case
        System.IO.File.Move(file, file.ToLower());

        // now show upper case directory names
        string dir = Path.GetDirectoryName(file);
        Response.Write(dir + "
        Response.Write(dir.ToLower() + "

The script also renames the files to be lower case, but the directory names are not changed. These have to be updated manually.

Once the files had been updated all the posts on this blog needed to be updated for any image src attributes to use the new lower case format.

The following code loops through all the blog posts and replaces the src attributes with lower case versions.

// Update database records
using (DataSet ds = new DataSet())
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Blog"].ConnectionString))
        SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(new SqlCommand("SELECT  * FROM Posts  ORDER BY DateCreated DESC", conn));
        mySqlDataAdapter.Fill(ds, "Posts");

        // loop database rows
        foreach (DataRow dr in ds.Tables["be_Posts"].Rows)
            RunSqlUpdate("Posts", new Object[,] { { "PostContent", RenameSrc(dr["PostContent"].ToString()), SqlDbType.Text } }, "PostRowID", Int32.Parse(dr["PostRowID"].ToString()));

The following function used regex to find and replace all src attributes:

public string RenameSrc(string text)
        // Function to find all src tags and replace with lower case text.
        string rmhttp = "src=['|\"](?.*?)['|\"]";
        System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(text, rmhttp);
        for (int icnt = 0; icnt < mc.Count; icnt++)
            text = text.Replace(mc[icnt].ToString(), "src=\"" + mc[icnt].Groups["url"].Value.ToLower() + "\"");

        return text;


To update the database I wrote this function which accepts an array of database fields and updates the data.


public void RunSqlUpdate(string TableName, Object[,] ob, string PrimaryName, int PrimaryValue)
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MainConn"].ConnectionString))

                StringBuilder sbQueryString = new StringBuilder();

                for (int i = 0; i < ob.GetLength(0); i++)
                    sbQueryString.Append(ob[i, 0] + "=@" + ob[i, 0]);
                    if (i < ob.GetLength(0) - 1) { sbQueryString.Append(","); }

                SqlCommand cmdIns = new SqlCommand("UPDATE " + TableName + " SET " + sbQueryString.ToString() + " WHERE " + PrimaryName + " = @" + PrimaryName, connection);
                for (int i = 0; i < ob.GetLength(0); i++)
                    cmdIns.Parameters.AddWithValue("@" + ob[i, 0], ob[i, 1]);

                cmdIns.Parameters.AddWithValue("@" + PrimaryName, PrimaryValue);

                cmdIns = null;
            catch (Exception ex)





Post your comment