Replace multiple characters in string (enter correct folder name)

For string and character array:

string userDir = WindowsIdentity.GetCurrent().Name;
char[] chars Path.GetInvalidPathChars();

      

If you want to replace all characters in "chars" in the string "userDir" to make the username a valid directory name. Or can I assume that each username is a valid directory?

The best idea I've created so far is two loops ... but I'm looking for a shorter solution.

Or is there another method to create a valid directory name?

+3


source to share


3 answers


Assuming your code:

string userDir = WindowsIdentity.GetCurrent().Name;
char[] chars = Path.GetInvalidPathChars();

      

You can always do:

Array.ForEach(chars, c => userDir = userDir.Replace(c, '_'));

      



To replace any invalid char with an underscore (or whatever neutral character you want ...).

UPDATE . As Steve Fallows pointed out, \

and :

are valid path characters, but not valid folder name characters. Instead, we should use the method Path.GetInvalidFileNameChars()

:

char[] chars = Path.GetInvalidFileNameChars();

      

And continue as before.

+7


source


// 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, "_");

      



+1


source


Based on comment by James Michael Hare, here is a slightly more robust version for fixing a line to be used as one level of folders in a path:

private string ReplaceInvalidFolderNameChars(string proposedFolderName_)
{
    char[] chars = Path.GetInvalidPathChars();
    Array.Resize(ref chars, chars.Length + 2);
    chars[chars.Length - 2] = ':';
    chars[chars.Length - 1] = '\\';
    Array.ForEach(chars, c => proposedFolderName_ = proposedFolderName_.Replace(c, '_'));
    return proposedFolderName_;
}

      

UPDATE : Simplified version based on James' update:

private string ReplaceInvalidFolderNameChars(string proposedFolderName_)
{
    char[] chars = Path.GetInvalidFilenameChars();
    Array.ForEach(chars, c => proposedFolderName_ = proposedFolderName_.Replace(c, '_'));
    return proposedFolderName_;
}

      

+1


source







All Articles