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:
string userDir = WindowsIdentity.GetCurrent().Name;
char[] chars = Path.GetInvalidPathChars();
You could always do:
Array.ForEach(chars, c => userDir = userDir.Replace(c, '_'));
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 the Path.GetInvalidFileNameChars() method:
char[] chars = Path.GetInvalidFileNameChars();
And then continue as before.
// This only needs to be initialized once.
var invalidChars = Path.GetInvalidPathChars().Select(c => Regex.Escape(c.ToString()));
Regex regex = new Regex(string.Join("|", invalidChars));
// Replace all invalid characters with "_".
userDir = regex.Replace(userDir, "_");
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