I am allowing the user to choose any username he wants and it can be anything at all such as
AC♀¿!$"Man'@
Now i need to create a directory for him. What function i use to escape the text so i dont a FS problem/exception?
I am allowing the user to choose any username he wants and it can be anything at all such as
AC♀¿!$"Man'@
Now i need to create a directory for him. What function i use to escape the text so i dont a FS problem/exception?
Use Path.GetInvalidFileNameChars
or Path.GetInvalidPathChars
to check for characters to remove.
http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx
Whether you replace invalid characters or remove them, there's always going to be the possibility of collisions. If I were you, I'd have a separate primary key for the user (a GUID perhaps) and use that for the directory name. That way you can have your user names anything you'd like without worrying about invalid directory names.
Depending on if your characters are ASCII/Unicode, you can use the byte/character values as a replacement and use some character to mark these replaced characters (like an underscore), giving you something like _001_255_200ValidPart_095_253
. Note that you have to replace the marking characters, too (_095
in the example, 95 is the ASCII code for the underscore).
I think your best bet would be to create a Dictionary that maps invalid filesystem characters to a valid replacement string. Then scan the string for invalid characters, replacing with valid strings as you go. This would allow the user to pick anything they want and give you the consistency to translate it back into the user's name if you want.
You're not going to find a way to escape the username that will give a valid non-clashing directory name in every instance.
A more reliable approach will be to create the directory using some arbitary convention, and then store a mapping between the two. This also provides support for the case where your user wants the ability to change name.
Check out Question #663520 for more on this.
does user need to know the exact name of his / her directory ? If not, why not create directories using arbitrary rules and associate each one to his owner in a DB or something ?