Say, I have two path strings, an absolute one such as @"C:\abc\xyz"
, and a relative one such as @"..\def"
. How do I reliably combine those to yield the minimal form @"C:\abc\def"
?
As the process should work for any forms of path that .NET's I/O API supports (i.e. the native paths of the system that .NET or Mono is currently running on, or alternatively something like UNC paths and the like), manual string manipulation seems to be too unreliably a solution.
In general, the tidy way to combine path strings is to use the Path.Combine
method:
Path.Combine(@"C:\abc\xyz", @"..\def")
Unfortunately, it does not minimize the path and returns C:\abc\xyz\..\def
.
As is suggested in a couple of other questions (e.g. this, or this), the GetFullPath
method should be applied to the result:
Path.GetFullPath(Path.Combine(@"C:\abc\xyz", @"..\def"))
The problem with this is that GetFullPath
actually looks at the file system rather than just handling the path string. From the docs:
The file or directory specified by path is not required to exist. (...) However, if path does exist, the caller must have permission to obtain path information for path. Note that unlike most members of the Path class, this method accesses the file system.
Therefore, GetFullPath
doesn't work if I just want to minimize arbitrary path strings: Depending on whether the path happens to exist on the system where the application is running, the method might fail with a SecurityException
if the user does not have access to the path.
So, how do I reliably combine path strings that could be processed by System.IO
methods to return the shortest possible absolute path?
You can use AbsolutePath of Uri class
If you want to use it via
System.IO
you will run into access violation problems at that point.Why bother to increase the time till the exception comes?
Use
try {} catch {}
aroundGetFullPath
and handle the error in place would be my suggestion.