简体   繁体   English

Windows 文件名 - 如何检查文件名是否有效?

[英]Windows filename - How to check if filename would be valid?

I wanted a function, possibly amongst Path Functions , that would check if file-name would be valid.我想要一个函数,可能在Path Functions 中,它会检查文件名是否有效。 By valid, I meant if character present in the string are all valid (having no ? , > etc, for example).通过有效,我的意思是字符串中存在的字符是否都是有效的(例如,没有?>等)。 But sadly, there is no function.但遗憾的是,没有任何功能。 Browsing through the net, and SO, I found few techniques, none of them I liked, or found solid.浏览网络,所以,我发现了一些技术,我不喜欢它们,或者发现它们是可靠的。

  • Using a regular expression to check the contents of filename.使用正则表达式检查文件名的内容。
  • Creating a file name, possibly in %TEMP% path of the system.创建文件名,可能在系统的%TEMP%路径中。 If creation fails, the filename is ( possibly ) invalid.如果创建失败,则文件名(可能)无效。 Otherwise, it is valid (and therefore, delete the file).否则,它是有效的(因此,删除该文件)。
  • Write up a function, that checks if invalid characters are present in the filename (eg ?:*> )编写一个函数,检查文件名中是否存在无效字符(例如?:*>

An extended form of function would be to check all invalid names (like AUX , CON etc), but that's not an issue (at least for now).功能的扩展形式是检查所有无效名称(如AUXCON等),但这不是问题(至少现在是这样)。

Is there any documented/undocumented function, that I might have missed, which would reliably check if filename ( not pathname) is valid.是否有任何记录/未记录的功能,我可能错过了,它可以可靠地检查文件名(不是路径名)是否有效。

Edit: the PathCleanupSpec function is now deprecated and no longer supported.编辑: PathCleanupSpec函数现已弃用且不再受支持。 Refer to the Requirements section at the end of the linked page for details.有关详细信息,请参阅链接页面末尾的“ Requirements部分。


Thanks Connor, for the function.感谢康纳的功能。 For other readers, the function name is PathCleanupSpec .对于其他读者,函数名称是PathCleanupSpec Using which I have implemented following:使用我已经实现了以下内容:

bool IsLegalFileName(LPCWSTR filename)
{
    WCHAR valid_invalid[MAX_PATH];
    wcscpy_s(valid_invalid, filename);

    int result = PathCleanupSpec(nullptr, valid_invalid);

    // If return value is non-zero, or if 'valid_invalid' 
    // is modified, file-name is assumed invalid
    return result == 0 && wcsicmp(valid_invalid, filename)==0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM