Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

c# - Blank space after file extension -> weird FileInfo behaviour

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.

The error manifests here:

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

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.

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ending file names with a space is documented as a Bad Idea.

From MSDN "Naming Files, Paths, and Namespaces (Windows)":

  • Do not end a file or directory name with a space or a period. Although the underlying file system may support such names, the Windows shell and user interface does not.

Also, the KB article "INFO: Filenames Ending with Space or Period Not Supported":

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 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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...