2

This question has been asked before but I don't seem to see my exact solution. I need to traverse some links in a file that are using relative paths and check whether or not they link to files that exist. Given the following files and folders:

C:\Level 1\Level 2\A.txt
C:\Level 1\B.txt

There might be a link in A.txt that links to B.txt using the relative path ..\B.txt.

I will have the current traversing directory, C:\Level 1\Level 2, and need to combine that with ..\B.txt to come up with C:\Level 1\B.txt so I can check the existence of B.txt.

I tried using Path.Combine but that didn't work. Any other thoughts? It would need to be able to support multiple levels like ..\..\..\D.txt.

1
  • 1
    What didn't work with Path.Combine? Given the paths that you described, Path.Combine returned "C:\Level 1\Level 2\..\B.txt", which is a perfectly valid path that you can pass to File.Exists. Commented Jul 19, 2013 at 4:01

1 Answer 1

6

Path.Combine should work fine with "." and ".." relative paths. If you were to have two strings, path1 = "C:\Level 1\Level 2" and path2 = "..\B.txt" and then call Path.Combine(path1, path2), the returned string would be "C:\Level 1\Level 2\..\B.txt", which will function as a path in .NET. You can then take that string and call File.Exists on it to confirm if the file at that combined path exists.

If you want to resolve the relative path component ".." in Path.Combine's output, taking the initial output from Path.Combine and passing it into Path.GetFullPath will transform it into a proper absolute path. File.Exist will accept either form. If it's not accepting it for some reason, the issue might be with the paths being passed into Path.Combine. If that's the case, I would examine them with the debugger and see what's going on.

Sign up to request clarification or add additional context in comments.

2 Comments

I guess I just stopped short. I saw Path.Combine return "C:\Level 1\Level 2\..\B.txt" and figured that wouldn't work but I didn't even try. I will test it out. Thanks.
Yeah, I can understand that. I think I felt the same way when I first used Path.Combine on paths like that. It's technically a functioning path in Windows though, and .NET will accept it. If you prefer the path resolved to an absolute one for completeness, just call Path.GetFullPath.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.