I\'ve got a string like \"Foo: Bar\" that I want to use as a filename, but on Windows the \":\" char isn\'t allowed in a filename.
Is there a method that will turn \
In case anyone wants an optimized version based on StringBuilder, use this. Includes rkagerer's trick as an option.
static char[] _invalids;
/// Replaces characters in text that are not allowed in
/// file names with the specified replacement character.
/// Text to make into a valid filename. The same string is returned if it is valid already.
/// Replacement character, or null to simply remove bad characters.
/// Whether to replace quotes and slashes with the non-ASCII characters ” and ⁄.
/// A string that can be used as a filename. If the output string would otherwise be empty, returns "_".
public static string MakeValidFileName(string text, char? replacement = '_', bool fancy = true)
{
StringBuilder sb = new StringBuilder(text.Length);
var invalids = _invalids ?? (_invalids = Path.GetInvalidFileNameChars());
bool changed = false;
for (int i = 0; i < text.Length; i++) {
char c = text[i];
if (invalids.Contains(c)) {
changed = true;
var repl = replacement ?? '\0';
if (fancy) {
if (c == '"') repl = '”'; // U+201D right double quotation mark
else if (c == '\'') repl = '’'; // U+2019 right single quotation mark
else if (c == '/') repl = '⁄'; // U+2044 fraction slash
}
if (repl != '\0')
sb.Append(repl);
} else
sb.Append(c);
}
if (sb.Length == 0)
return "_";
return changed ? sb.ToString() : text;
}