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 \
Cleaning a little my code and making a little refactoring... I created an extension for string type:
public static string ToValidFileName(this string s, char replaceChar = '_', char[] includeChars = null)
{
var invalid = Path.GetInvalidFileNameChars();
if (includeChars != null) invalid = invalid.Union(includeChars).ToArray();
return string.Join(string.Empty, s.ToCharArray().Select(o => o.In(invalid) ? replaceChar : o));
}
Now it's easier to use with:
var name = "Any string you want using ? / \ or even +.zip";
var validFileName = name.ToValidFileName();
If you want to replace with a different char than "_" you can use:
var validFileName = name.ToValidFileName(replaceChar:'#');
And you can add chars to replace.. for example you dont want spaces or commas:
var validFileName = name.ToValidFileName(includeChars: new [] { ' ', ',' });
Hope it helps...
Cheers