How to get minimal absolute path from relative pat

2019-07-15 08:33发布

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?

2条回答
叛逆
2楼-- · 2019-07-15 08:43

You can use AbsolutePath of Uri class

var path = new Uri(Path.Combine(@"C:\abc\xyz", @"..\def")).AbsolutePath;
查看更多
欢心
3楼-- · 2019-07-15 08:56

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 {} around GetFullPath and handle the error in place would be my suggestion.

So, how do I reliably combine path strings that could be processed by System.IO methods to return the shortest possible absolute path?

查看更多
登录 后发表回答