文件扩展名后的空格 - >怪异的FileInfo行为空格、怪异、文件扩展名、行为

2023-09-03 01:00:23 作者:旧时伊人旧时裳

不知怎的,一个文件已经出现在我的目录之一,它有空间在其延伸的末端 - 它的名字是的test.txt。奇怪的是, Directory.GetFiles()我返回此路径 文件,但我无法检索与 FileInfo的文件信息类。

Somehow a file has appeared in one of my directories, and it has space at the end of its extension - its name is "test.txt ". The weird thing is that Directory.GetFiles() returns me the path of this file, but I'm unable to retrieve file information with FileInfo class.

错误体现在这里:

DirectoryInfo di = new DirectoryInfo("c:\\somedir");
FileInfo fi = di.GetFileSystemInfos("test*")[0] as FileInfo; 
//correctly fi.FullName is "c:\somedir\test.txt "
//but fi.Exists==false (!)

时的FileInfo类坏了吗?我能以某种方式检索有关该文件的信息?我真的不知道这是怎么的文件出现在我的文件系统,我无法重新创建一些更多的人。

Is FileInfo class broken? Can I somehow retrieve information about this file? I really don't know how did that file appear on my file system, and I am unable to recreate some more of them.

我所有的尝试创建这种类型的扩展名的新文件都失败了,但现在我的计划是 encoutering当它崩溃。我能找到的文件时容易处理异常,但是孩子是我 好奇这个!

All of my attempts to create a new file with this type of extension have failed, but now my program is crashing when encoutering it. I can easily handle the exception when finding the file, but boy am I curious about this!

推荐答案

结束的文件名用空格被记录为一个坏主意。

从MSDN 命名的文件,路径和命名空间(Windows)中:

  请不要结束一个文件或目录名用空格或句点。虽然底层的文件系统可以支持这样的名称,Windows外壳程序和用户界面没有。   

此外,知识库文章信息:文件名用空格或句号结尾不支持:

问题可能会出现。在code删除尾随空格和句号,不进行和Macintosh用户获取正确穿插文件名。在Win32 API的用FindFirstFile() FindNextFile()返回,在一个空间或在一段结尾的文件名;然而,没有办法来创建或使用Win32 API打开该文件。

Problems can arise when a Macintosh client creates a file on a Windows NT server. The code to remove trailing spaces and periods is not carried out and the Macintosh user gets the correctly punctuated filename. The Win32 APIs FindFirstFile() and FindNextFile() return a filename that ends in a space or in a period; however, there is no way to create or open the file using the Win32 API.

的DirectoryInfo 可能使用用FindFirstFile()和朋友产生目录列表。 File.Exists 是最有可能通过实施GetFileAttributes()这可能是由同一个问题遭受的的CreateFile()键,将报告不存在的文件。

DirectoryInfo probably uses FindFirstFile() and friends to produce directory listings. File.Exists is most likely implemented through GetFileAttributes() which probably suffers from the same problem as CreateFile() and will report a nonexistent file.

因此​​,在.NET不是一个问题特别,但在Windows本身。

Hence, not a problem in .NET specifically, but in Windows itself.