0

I've just found a bug in my application where Path.GetFullPath() does not return exactly the same result for different representations of the same path. In this case, ../include and ../include/ are returning c:\\...\\include & c:\\...\\include\\ respectively; since I maintain a Dictionary<string,...> for dir names this breaks things.

How can this be fixed, ideally without nastly kludgy checks on strings but using framework methods?

leppie
  • 115,091
  • 17
  • 196
  • 297
Mr. Boy
  • 60,845
  • 93
  • 320
  • 589

3 Answers3

4

../include may point to a directory or a file (files don't have to have an extension), and ../include/ always is a directory because of the trailing slash. So they are definitely not the same.

If you are sure the input always are directories (which Path.GetFullPath() can't be sure of), you can do:

path = Path.Combine(input, Path.DirectorySeparatorChar.ToString());

This way all input will be seen as directories, not files, and Path.GetFullPath() will return the same for both variants.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • In _this_ context, they _are_ the same... an external file has a list of additional dirs so if someone has put in a file-name, the data is bad in the first place. I already check the path is a valid directory explicitly. – Mr. Boy Feb 20 '13 at 13:46
  • Yes, you know that, but Path.GetFullPath() doesn't, because that's a string operation, not a filesystem operation. Just make all paths end with a trailing slash then to help it a little. – CodeCaster Feb 20 '13 at 13:50
  • Or sorry, I see what you mean. Shouldn't `@"\"` be the proper dir-separator constant though, strictly speaking? – Mr. Boy Feb 20 '13 at 14:15
  • @John yes, that would even be cleaner, look at [`Path.DirectorySeparatorChar`](http://msdn.microsoft.com/en-us/library/system.io.path.directoryseparatorchar.aspx)`.ToString()`. – CodeCaster Feb 20 '13 at 14:24
  • I need to correct my string vs filesystem remark: _" Note that unlike most members of the Path class, this method accesses the file system. "_ – CodeCaster Feb 20 '13 at 16:54
0

They shouldn't return the same result. If you need to check if the path is actually a file or a directory you can use Path.GetFullPath("../include") Without the trailing slash. If the paths are provided programatically then do a string.TrimEnd('\\') and then check if the path is a file or a directory using:

File.Exists() and Directory.Exists() to determine if the specified path is a file or a directory.

You need to make sure that all your table insertions and searching is done by inserting/comparing with non trailing slash paths.

Zaid Amir
  • 4,727
  • 6
  • 52
  • 101
0

do a .TrimEnd('\') if it's plausible.

Rui Lima
  • 7,185
  • 4
  • 31
  • 42