安全/允许文件名清洁剂对.NET清洁剂、文件名、安全、NET

2023-09-03 03:57:48 作者:等我前途伟大炸了清华北大

有没有什么标准/ libraried /测试方法在.NET中采取一种任意的字符串和裂伤它以这样一种方式,它重新presents有效的文件名?

Is there any standardized / libraried / tested way in .NET to to take an arbitrary string and mangle it in such a way that it represents a valid file name?

我自己的滚动字符替换功能很容易,但我想的东西多一点健壮和resued。

Rolling my own char-replace function is easy enough, but I'd like something a little more robust and resued.

推荐答案

这个问题并不像你想像的那么简单。不仅是在 Path.GetInvalidFileNameChars 字符非法,有几个文件名,例如PRN和CON,由Windows保留的,不能被创建。在结尾的名称。也是在Windows非法的。此外,有各种长度的限制。阅读完整名单这里。

This problem is not as simple as you may think. Not only are the characters in Path.GetInvalidFileNameChars illegal, there are several filenames, such as "PRN" and "CON", that are reserved by Windows and cannot be created. Any name that ends in "." is also illegal in Windows. Moreover, there are various length limitations. Read the full list here.

如果这还不够,不同的文件系统有不同的限制,例如ISO 9660名不能以 - ,但也包含它

If that's not enough, different filesystems have different limitations, for example ISO 9660 filenames cannot start with "-" but can contain it.