c# - Directory.GetFiles 查找不存在的文件

标签 c# .net windows file getfiles

我刚刚偶然发现 System.IO.Directory 中的 GetFiles 方法的一个未记录的行为。

每当传递给该方法的 searchPattern 参数包含保留的 Windows 设备名称,例如 "nul.*""aux.bmp",该方法返回一个数组,其中包含一个不存在的文件的名称,如 C:\Users\ft1\nulD:\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/

相关文章:

c# - 将 DataTable 中的列值从 byte[] 转换为 String

.net - 在分布式事务中手动登记后,使用 enlist=false 的连接不会关闭

.net - 64 位 .NET Informix ADO.NET 提供程序的程序集加载错误

c# - 如何使用列表和关系对象测试 fluent-NHibernate 的 PersistenceSpecification.VerifyTheMappings?

windows - Windows 线程何时需要消息循环,为什么?

windows - 如何从命令提示符快速打开当前目录?操作系统 - Windows

windows - C :\Users\' is not recognized as an internal or external command compiling opencv for QT

c# - Linq to Sql 中的子查询

c# - XML 文件 C# 中的错误保存

c# - 字典如何在 GC 之后找到对象?