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 "Foo: Bar" into something like "Foo- Bar"?
Don't start or end your filename with a space, period, hyphen, or underline. Keep your filenames to a reasonable length and be sure they are under 31 characters. Most operating systems are case sensitive; always use lowercase. Avoid using spaces and underscores; use a hyphen instead.
A special character is a letter or symbol that cannot be used in file names because it is being utilized in another location or by the operating system.
File names can contain any of the following characters: A-Z, a-z, 0-9, underscore, hyphen, space, period, parenthesis, curly braces, square brackets, tilde, exclamation point, comma, semicolon, apostrophe, at sign, number sign, dollar sign, percent sign, plus sign, and equal sign.
Try something like this:
string fileName = "something"; foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { fileName = fileName.Replace(c, '_'); }
Edit:
Since GetInvalidFileNameChars()
will return 10 or 15 chars, it's better to use a StringBuilder
instead of a simple string; the original version will take longer and consume more memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With