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"?
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"?
Replace characters in your string, perhaps? Depends on what functions are available to you. You can map characters which are not allowed in filenames (such as ':') to those which are (such as '-'). Very simple task.
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.
fileName = fileName.Replace(":", "-")
However ":" is not the only illegal character for Windows. You will also have to handle:
/, \, :, *, ?, ", <, > and |
These are contained in System.IO.Path.GetInvalidFileNameChars();
Also (on Windows), "." cannot be the only character in the filename (both ".", "..", "...", and so on are invalid). Be careful when naming files with ".", for example:
echo "test" > .test.
Will generate a file named ".test"
Lastly, if you really want to do things correctly, there are some special file names you need to look out for. On Windows you can't create files named:
CON, PRN, AUX, CLOCK$, NUL
COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9
LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.
Diego does have the correct solution but there is one very small mistake in there. The version of string.Replace being used should be string.Replace(char, char), there isn't a string.Replace(char, string)
I can't edit the answer or I would have just made the minor change.
So it should be:
string fileName = "something";
foreach (char c in System.IO.Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(c, '_');
}