4

If you have a path like "C:\foo\.\bar\.." is there an easy way using the Win32 API to remove the directory qualifiers in order to simplify it to "C:\foo" ?


Update: It seems to be a more complicated issue. On this simple example of "C:\foo\.\bar\..", it works with both PathCanonicalize() and GetFullPathName() to get "C:\foo" as a result.

However, the path I'm passing has a symbolic link. So let's say I'm passing in "C:\NaNa\Boo\Bin\.." and "C:\NaNa" is a link to "D:\Apple". Then I get "C:\NaNa\Boo\Bin\.." back ratener than "C:\NaNa\Boo"

I would assume the functions work with just the strings but there seems to be a difference when using the symbolic link :-(


Update #2: It appears I had a line break character (0x0d) in the string that was passed in and this kept the function from working properly!

Adisak
  • 6,708
  • 38
  • 46
  • 1
    I want to apologize to the person who posted GetFullPathName() as an answer when I commented that didn't work (and they pulled their response). It actually does work with a correctly formatted string. At least I only commented rather than downvoting but I still feel an apology is warranted. – Adisak Jul 06 '11 at 20:58

1 Answers1

8

Take a look at shlwapi's PathCanonicalize()

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • For some reason, on my machine (Windows 7), PathCanonicalize() is not removing the trailing ".." - curious because the docs imply it should. – Adisak Jul 06 '11 at 16:14
  • Odd, works for me on xp, the `buffer_5[]`example @ msdn shows trailing .. being stripped – Alex K. Jul 06 '11 at 16:16
  • Hmm it works for "c:\foo\.\bar\.." -- it just doesn't seem to work for my real longer directory name. – Adisak Jul 06 '11 at 16:23
  • FWIW, GetFullPathName() works for the "c:\foo\.\bar\.." example too. For my realworld example, I am using a pathname with a symbolic link in it though. – Adisak Jul 06 '11 at 16:27
  • The problem turned out to be a bad character in the input string. Thanks for the help. – Adisak Jul 06 '11 at 20:58
  • 2022 update: [PathCchCanonicalizeEx](https://learn.microsoft.com/en-us/windows/win32/api/pathcch/nf-pathcch-pathcchcanonicalizeex) performs a few extra tricks and, used properly, can prevent buffer overruns. – user4581301 Jun 04 '22 at 16:53