文件系统文件名转义? C#
我允许用户选择他想要的任何用户名,并且可以是任何用户名,例如
AC♀¿!$"Man'@
现在我需要为他创建一个目录。 我使用什么函数来转义文本,这样我就不会出现 FS 问题/异常?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用 Path.GetInvalidFileNameChars 或 Path.GetInvalidPathChars 检查是否有要删除的字符。
http://msdn.microsoft.com/en-我们/library/system.io.path.getinvalidfilenamechars.aspx
Use
Path.GetInvalidFileNameChars
orPath.GetInvalidPathChars
to check for characters to remove.http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx
我认为最好的选择是创建一个字典,将无效的文件系统字符映射到有效的替换字符串。 然后扫描字符串中的无效字符,并随时替换为有效字符串。 这将允许用户选择他们想要的任何内容,并为您提供一致性,以便您可以根据需要将其翻译回用户名。
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.
您不会找到一种方法来转义用户名,从而在每个实例中提供有效的非冲突目录名称。
更可靠的方法是使用某种任意约定创建目录,然后存储两者之间的映射。 这还为您的用户希望能够更改名称的情况提供支持。
查看问题# 663520 了解更多信息。
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 ?
无论您替换无效字符还是删除它们,总是存在发生冲突的可能性。 如果我是你,我会为用户设置一个单独的主键(可能是 GUID)并将其用作目录名称。 这样您就可以为您的用户命名任何您想要的名称,而不必担心无效的目录名称。
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.
根据您的字符是否为 ASCII/Unicode,您可以使用字节/字符值作为替换,并使用某些字符来标记这些替换的字符(如下划线),为您提供类似
_001_255_200ValidPart_095_253
的内容。 请注意,您还必须替换标记字符(示例中的_095
,95 是下划线的 ASCII 代码)。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).