Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a valid Windows filename from an arbitrary string?

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"?

like image 875
Ken Avatar asked Mar 06 '09 22:03

Ken


People also ask

How do I make a file name valid?

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.

Can filename have special characters?

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.

What is a valid filename?

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.


1 Answers

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.

like image 87
Diego Jancic Avatar answered Oct 11 '22 02:10

Diego Jancic