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;
}