C# Code Snippet: Ensure Filename is Unique

OK, this is not exactly going to be the most complicated C# code snippet you will ever see. I’ve often wondered why the .NET Framework does not include similar functionality to Explorer when copying and pasting files (if it does and I’ve somehow missed it, please post a comment and let me know!). I’ve often needed the simple logic of ensuring that saving a file to a specified folder does not clash with one of the same name. There are basically two ways of doing this: (1) simply modify the filename to include a string representation of a GUID (via Guid.NewGuid().ToString()), or (2) or modify the filename to prepend something like “Copy (?) of “ checking until the name is unique. Here is a minimalist implementation of the second:

/// 
/// See main overload.
/// 
/// a fully pathed filename
/// a unique fully pathed filename
public static string EnsureUniqueFilename(string fullFilePathname)
{
    string destFolder = Path.GetDirectoryName(fullFilePathname);
 
    if (String.IsNullOrEmpty(destFolder))
        throw new ArgumentException("You must pass a fully pathed filename");
 
    return EnsureUniqueFilename(fullFilePathname, destFolder);
}
 
/// 
/// Return a unique filename of the form, 'Copy of (?) OriginalFilename.ext'
/// NOTE: Does not adhere to the full semantics of the file explorer copy logic.
///       which creates first copy named as 'Copy of OriginalFilename.ext'
///       Nor does it rename any files. It simply returns a filename which is unique
///       It does not take into account multiple threads attempting to make use 
///       of the same filename.
/// 
/// a fully pathed filename
/// a destination folder
/// a unique fully pathed filename
public static string EnsureUniqueFilename(string fullFilePathname, string destFolder)
{
    string filename = Path.GetFileName(fullFilePathname);
    string renamedFile = Path.Combine(destFolder, Path.GetFileName(fullFilePathname));
 
    // Check if a file with same name exists in folder and try a modified name if neccessary...
    int intCopy = 0;
    while (File.Exists(renamedFile))
    {
        intCopy++;
        renamedFile = Path.Combine(destFolder, "Copy (" + intCopy.ToString() + ") of " + filename);
    }
 
    return renamedFile;
}

Photoshop Tutorials

Mastering PhotoShop seems to take a lifetime. Not that I would put myself in that esteemed camp. I came across a few surprisingly easy but effective tutorials at the Photoshop Café here and here.

If you are a keen photographer, it’s hard to pass up this gem of a book The Photoshop CS Book for Digital Photographers by Scott Kelby. If you can find a better hands-on book, buy it and please let me know what it is! Here’s just one very simple tip of many more involved examples from the book: to display your work press ‘f’, ‘f’ and then ‘Tab’. The first ‘f’ centers your work; the second hides the menu bar and displays a black background. ‘Tab’ hides the toolbars, Options bar and palettes. Just press ‘f’ and ‘Tab’ to return to normal working mode.

Code Snippets

Nick followed up on my C# snippet post with a nice piece about using code snippets in Visual Studio 2005 and using a snippet editor to create and share your own code snippets. His post reminded me that I had forgotten to mention that to use that snippet you will need to add a “using System.Data.SqlClient;” and System.Data to your references.

Nick mentioned the VB.NET version of the code snippets editor; you can download Snippy, a Visual Studio C# Snippet Editor from GotDotNet (soon to disappear; come on Microsoft, I’m sure it wouldn’t break the bank to keep this running. I ask myself if Google would close down a similar site…) [BTW, Brian Madsen one of our other Perth MVP’s loves VB.NET with a passion. He is going to kill me for saying that :)… ]

I was also going to recommended having a look at the gotcodesnippets.com site but the second C# snippet I looked at was flawed: don’t use the singleton that is posted there. It’s not thread safe. Use this one instead: C# Singleton Best Practice. The gotcodesnippets site could be improved by having some sort of comment or peer review voting system (similar to regexlib, for example), otherwise it is in danger of spreading incorrect information. I suppose this is always the danger with such open sites. I’m sure there are many useful snippets there; just don’t go using them without checking first. One nice feature is that the site is RSS enabled so you can be notified of new code snippet uploads.

Free Developer E-Learning

One of the developer resources that I’ve mentioned a few times on my blog are the free e-learning courses Microsoft provide. There are several currently available:

Branching Guidance for Team Foundation Server

Jeff Beehler has announced the initial release of Branching guidance for Team Foundation Server:

“While the product documentation will tell you how each of our tools works, it
doesn’t provide insight into the best practice usage of each. The guidance
that we recently released attempts to fill that gap in the area of version
control and how to best work with branches. … what you’ll read in this
guidance isn’t some theoretical description of how things should work in a
perfect world but instead has been pressure tested and proved to be effective
through actual TFS projects. In fact, you’ll find examples pulled directly
from our own teams experiences as well. ”

I found it interesting that they appear to have moved away from what I assumed was the industry standard terminology of ‘trunk’ to ‘main’. Much of the advice is familiar. The few differences I suspect are down to working in very large teams (> 100 developers). This is a work in progress, and I’m sure a few changes will be made to it…

The best source of advice on branching and merging that I have come across to date is the free online book Version Control with Subversion. I wonder if the authors read this?

C# Code Snippet: Read Data from Stored Procedure

I love clear, concise, easy to read code. Here’s a fairly minimalist .NET 2.0 code snippet to read data using a stored procedure that is hopefully all those things. It makes use of the using statement which guarantees that resources held by types that implement IDisposable will be released even if an exception is thrown (using is syntactic sugar for an enclosing try/catch/finally loop):

// Execute a stored proc to read data
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "ProcName";
        cmd.CommandType = CommandType.StoredProcedure;
 
        // Add any input Params...
        cmd.Parameters.AddWithValue("@SomeIDParam", myID);
 
        conn.Open();
 
        // Assuming Stored Proc returns a set of records...
        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            while (rdr.Read())
            {
                // do something with each rdr row ... 
            }
        }
 
        // OR alternatively, 
        // if your proc returns a single valued result (e.g. an image)
        // (i.e. query of the form "SELECT imgColumnName FROM Table WHERE ID= ?"
        // byte[] img = (byte[])cmd.ExecuteScalar();  
    }
}