我刚刚偶然发现 System.IO.Directory
中的 GetFiles
方法的一个未记录的行为。
每当传递给该方法的 searchPattern
参数包含保留的 Windows 设备名称,例如 "nul.*"
或 "aux.bmp"
,该方法返回一个数组,其中包含一个不存在的文件的名称,如 C:\Users\ft1\nul
或 D:\aux
等。
我想知道这些设备名称在上下文中是否有特殊含义,例如“。”或“..”,或者这只是一种错误。无论如何,这看起来仍然很奇怪。 例如,C# 中的这段代码:
string[] fileNames = Directory.GetFiles(@"C:\D:\..\..\...\", "con.txt");
foreach (string fileName in fileNames) Console.WriteLine(fileName);
打印
C:\D:\..\..\...\con
有什么线索吗?
最佳答案
这是众所周知的。这是关于Naming Files, Paths, and Namespaces (Windows)的操作系统设计
Excerpt:
Do not use the following reserved names for the name of a file: CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names followed immediately by an extension; for example, NUL.txt is not recommended. For more information, see Namespaces.
这些基本上是文件名别名(命名空间),因此它们始终存在于全局(在每个文件夹中)。如果您尝试枚举它们,您将取回它们,因为它们确实存在。
关于c# - Directory.GetFiles 查找不存在的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14104451/