Filesystem filename escape? C#

风流意气都作罢 提交于 2019-12-05 05:30:48

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.

Bevan

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 ?

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