Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:\somedir\test.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!

like image 624
Axarydax Avatar asked Apr 30 '10 07:04

Axarydax


2 Answers

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.

like image 94
Thomas Avatar answered Oct 14 '22 18:10

Thomas


Yes i know of these files. I also got once such a beast thing. To get rid of it i don't know about a programming way in C#, but good old command line is your friend:

Open a console window in the given folder (or execute cmd and navigate to the folder with cd command). Now enter dir /x to retrieve the shortname of the files in this directory. Use this name to delete or rename the file by using the del or ren command.

like image 41
Oliver Avatar answered Oct 14 '22 19:10

Oliver