我知道/在Linux中是非法的,下面这些在Windows中是非法的 (我认为)*。" / \ []:;|,
我还遗漏了什么?
然而,我需要一份全面的指南,一份考虑到各种因素的指南 双字节字符。链接到外部资源对我来说很好。
我需要首先在文件系统上创建一个目录,其名称可能是 包含禁用字符,所以我计划将这些字符替换为 下划线。然后,我需要将这个目录及其内容写入一个zip文件 (使用Java),因此关于zip目录名称的任何其他建议 不胜感激。
我知道/在Linux中是非法的,下面这些在Windows中是非法的 (我认为)*。" / \ []:;|,
我还遗漏了什么?
然而,我需要一份全面的指南,一份考虑到各种因素的指南 双字节字符。链接到外部资源对我来说很好。
我需要首先在文件系统上创建一个目录,其名称可能是 包含禁用字符,所以我计划将这些字符替换为 下划线。然后,我需要将这个目录及其内容写入一个zip文件 (使用Java),因此关于zip目录名称的任何其他建议 不胜感激。
当前回答
这对我来说在Python中已经足够好了:
def fix_filename(name, max_length=255):
"""
Replace invalid characters on Linux/Windows/MacOS with underscores.
List from https://stackoverflow.com/a/31976060/819417
Trailing spaces & periods are ignored on Windows.
>>> fix_filename(" COM1 ")
'_ COM1 _'
>>> fix_filename("COM10")
'COM10'
>>> fix_filename("COM1,")
'COM1,'
>>> fix_filename("COM1.txt")
'_.txt'
>>> all('_' == fix_filename(chr(i)) for i in list(range(32)))
True
"""
return re.sub(r'[/\\:|<>"?*\0-\x1f]|^(AUX|COM[1-9]|CON|LPT[1-9]|NUL|PRN)(?![^.])|^\s|[\s.]$', "_", name[:max_length], flags=re.IGNORECASE)
还可以查看这个过时的列表,以获得FAT32中的=等其他遗留内容。
其他回答
对于任何寻找正则表达式的人:
const BLACKLIST = /[<>:"\/\\|?*]/g;
截至2017年4月18日,这个话题的答案中没有简单的字符和文件名的黑白列表,而且有很多回复。
我能想到的最好的建议是让用户随意命名文件。当应用程序试图保存文件时,使用错误处理程序,捕捉任何异常,假定是文件名造成的错误(显然在确保保存路径也正确之后),并提示用户输入新的文件名。为了获得最好的结果,将这个检查过程放在一个循环中,直到用户正确或放弃为止。对我来说是最好的工作(至少在VBA)。
要让Windows告诉你答案,最简单的方法是尝试通过资源管理器重命名文件,并输入反斜杠/作为新名称。Windows会弹出一个消息框,告诉你非法字符的列表。
A filename cannot contain any of the following characters:
\ / : * ? " < > |
微软文档-命名文件,路径和命名空间-命名约定
I always assumed that banned characters in Windows filenames meant that all exotic characters would also be outlawed. The inability to use ?, / and : in particular irked me. One day I discovered that it was virtually only those chars which were banned. Other Unicode characters may be used. So the nearest Unicode characters to the banned ones I could find were identified and MS Word macros were made for them as Alt+?, Alt+: etc. Now I form the filename in Word, using the substitute chars, and copy it to the Windows filename. So far I have had no problems.
下面是替换字符(Alt +十进制Unicode):
⃰ ⇔ Alt8432 ⁄ ⇔ Alt8260 ⃥ ⇔ Alt8421 ∣ ⇔ Alt8739 ⵦ ⇔ Alt11622 ⮚ ⇔ Alt11162 ‽ ⇔ Alt8253 ፡ ⇔ Alt4961 ‵‵ ⇔ Alt8246 “ ⇔ Alt8243
作为测试,我用所有这些字符组成了一个文件名,Windows接受了它。
在Windows 10(2019)中,输入以下字符时会出现错误,导致输入失败:
文件名不能包含以下字符: \ /: * ?< > |