Given a string and an array of chars:
string userDir = WindowsIdentity.GetCurrent().Name;
char[] chars Path.GetInvalidPathChars();
If want to replace all chars in “chars” in the “userDir” string to make an valid directory name out of the username. Or can I assume that every username is a valid directory?
The best idea I have yet is nesting two loops … but I’m looking for a shorter solution.
Or is there an other method to generate a valid directory name?
Assuming your code:
You could always do:
To replace any invalid char with an underscore (or whatever neutral character you’d like…).
UPDATE: As Steve Fallows indicated, the
\and:are valid path chars but not valid folder name chars. Instead, we should use thePath.GetInvalidFileNameChars()method:And then continue as before.