This is a quick one. Whenever I’m saving a file, I’m checking for two things: invalid characters in the filename and whether that filename already exists. You might be relying on one of the dialog components to help you, which is fine. I find myself often writing bulk-exports or filename suggestions, so this helps me.
These are a couple of functions that help me out.
I can never seem to find them when I need them, so I’m continually writing them again. But enough is enough, I’m putting it down on paper.
Let’s get started.
1. Replacing invalid characters
This replaces invalid characters with a “-” and returns “untitled”, if the filename is blank.
public string CleanFilename(string value, string defaultValue = "untitled", string replaceChar = "-")
{
if (string.IsNullOrWhiteSpace(value)) return defaultValue;
return string.Join(replaceChar, value.Replace(".", replaceChar).Split(Path.GetInvalidFileNameChars()));
}
2. Auto-naming for duplicate filenames
This adds a number (in brackets) at the end of duplicate filenames, starting at one. So, you’ll geta series of: “filename”, “filename (1)” and “filename (2)”.
public string AutoFilename(string filename)
{
if (!File.Exists(filename)) return filename;
string dir = Path.GetDirectoryName(filename);
string name = Path.GetFileNameWithoutExtension(filename);
string ext = Path.GetExtension(filename);
int n = 0;
string newFilename = null;
while (true)
{
n++;
newFilename = string.Concat(dir, "\\", name, " (", n.ToString(), ")", ext);
if (!File.Exists(newFilename))
{
break;
}
}
return newFilename;
}
Well, that’s that.
I hope someone finds this useful.
Posted on Thu 8th Jul 2021
Modified on Sat 12th Mar 2022