本文介绍了如何在没有任何权限检查的情况下从相对路径中获得最小的绝对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有两个路径字符串,一个绝对路径字符串(例如@"C:\abc\xyz")和一个相对路径字符串(例如@"..\def").我如何可靠地结合它们以产生最小形式@"C:\abc\def"?

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"?

由于该过程适用于.NET I/O API支持的任何形式的路径(即.NET或Mono当前正在运行的系统的本机路径,或者类似UNC路径之类的东西),手动字符串操作似乎太不可靠了.

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.

通常,组合路径字符串的整洁方法是使用 Path.Combine方法:

In general, the tidy way to combine path strings is to use the Path.Combine method:

Path.Combine(@"C:\abc\xyz", @"..\def")

不幸的是,它不会最小化路径并返回C:\abc\xyz\..\def.

Unfortunately, it does not minimize the path and returns C:\abc\xyz\..\def.

正如其他一些问题所建议的(例如,),则 GetFullPath方法应该应用于结果:

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"))

此问题是GetFullPath实际上查看文件系统,而不是仅处理路径字符串.从文档:

The problem with this is that GetFullPath actually looks at the file system rather than just handling the path string. From the docs:

因此,如果我只想最小化任意路径字符串,则GetFullPath不起作用:根据路径是否恰好在运行应用程序的系统上存在,如果该方法可能会失败,并显示SecurityException用户无权访问该路径.

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.

那么,我如何可靠地组合System.IO方法可以处理的路径字符串以返回尽可能短的绝对路径?

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

推荐答案

您可以使用Uri类的AbsolutePath

You can use AbsolutePath of Uri class

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

这篇关于如何在没有任何权限检查的情况下从相对路径中获得最小的绝对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:09