Filesystem filename escape? C#

最后都变了- 提交于 2020-01-02 02:41:58

问题


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?


回答1:


Use Path.GetInvalidFileNameChars or Path.GetInvalidPathChars to check for characters to remove.

http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx




回答2:


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.




回答3:


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).




回答4:


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.




回答5:


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.




回答6:


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 ?



来源:https://stackoverflow.com/questions/1021022/filesystem-filename-escape-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!