How to get minimal absolute path from relative path without any permission checks?

风格不统一 提交于 2019-12-11 02:20:50

问题


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?


回答1:


You can use AbsolutePath of Uri class

var path = new Uri(Path.Combine(@"C:\abc\xyz", @"..\def")).AbsolutePath;



回答2:


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?



来源:https://stackoverflow.com/questions/46629952/how-to-get-minimal-absolute-path-from-relative-path-without-any-permission-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!