Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple chars in string (Make valid folder name)

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?

like image 958
Tarion Avatar asked Feb 15 '26 16:02

Tarion


2 Answers

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.

like image 143
James Michael Hare Avatar answered Feb 18 '26 04:02

James Michael Hare


// 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, "_");
like image 26
Douglas Avatar answered Feb 18 '26 06:02

Douglas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!