Apparent bugs in System.IO.File.Exists and System.IO.FileInfo path handling

  • Thread starter Thread starter brant.usenet
  • Start date Start date
B

brant.usenet

Forgive me if this has already been covered; I've searched and found
nothing related.

File.Exists() seems to clean up the path passed into its path
parameter. Specifically, it seems to 'fix' any directory names within
the path with leading or trailing spaces.

E.g. assuming a file exists at "c:\foo\bar.txt"
File.Exists(@"C:\foo\bar.txt); --> true (OK)
File.Exists(@"C:\foo \bar.txt); --> true (incorrect)

Likewise, the FileInfo class constructor seems to do the same cleanup:

E.g. assuming a file exists at "c:\foo\bar.txt"
FileInfo f1 = new FileInfo(@"C:\foo\bar.txt");
FileInfo f2 = new FileInfo(@"C:\foo \bar.txt");
f1.Exists --> true (OK)
f1.FullName --> "C:\foo\bar.txt" (OK)
f2.Exists --> true (no)
f2.FullName --> "C:\foo\bar.txt" (!!!)

This is all very accomodating, but when testing for existance of a file
at a particular path, one would almost certainly prefer a more literal
result. Or, to at least have an option for such a literal test.

There are similar issues with Directory.CreateDirectory(). It will
silently fix up one's path and return success, leaving the caller to
believe that their (admittedly bogus) path was OK.

Can anyone tell me authoritatively that this is not by design? If it is
somehow by design, by what logic? How should I perform the test I
desire?
 
Interesting.

But, try this:

In Window Explorer, try to rename a folder name by appending a few "SPACE"
at the end of a folder name. Windows will alway trim off the SPACEs at the
end.

Also, if you set Windows Explorer to hide file name extension of known file
type, when you add SPACEs at the end of the file name, they get trimed
automatically, too; while if the file extension is shown, you can append
SPACE the the end of file name (before the extension).

I guess, this behaviour of Windows is by design, not a .NET bug. At least
when .NET runs on Windows platform.
 
Offhand I'd imagine that this is a built-in behaviour to help stop
cononicalization attacks.
 
That's fine & dandy for Explorer to do, but if one calls
System.IO.File.Exists(path), one should be told if a file exists at
'path'. Anything more is second guessing the caller. At the *very
least*, if it is indeed intentional, this behavior should be documented.
 
Thank you Adam, I'll do that and post any interesting results back
here.
Best,
Brant
 
Back
Top