C # 中绝对路径的相对路径?

我有一些 xml 文件,它们包含到图像的 href 文件路径(例如“ ... . images image.jpg”)。Hefs 包含相对路径。现在,我需要提取映像的 href 并将它们转换为文件系统中的绝对路径。

我知道 GetFullPath 方法,但是我试过了,它似乎只能在 CurrentDirectory 集合中工作,看起来是 C: 所以我不知道如何使用它。而且,我还有包含 href 的文件的绝对路径,以及 href 的相对路径,因此,对我来说,根据包含文件的绝对路径来计算“ ... ...”部分的数量是一个简单的任务,所以似乎必须有一种方法来以编程的方式来做这件事。

我希望有一些简单的方法,我只是不知道! 有什么想法吗?

162133 次浏览

You can use Path.Combine with the "base" path, then GetFullPath on the results.

string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, @"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath);  // Will turn the above into a proper abs path

Have you tried Server.MapPath method. Here is an example

string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg

Assuming you know the real directory the XML file lives in use Path.Combine, e.g.

var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");

If you want to get back the full path with any ..'s collapsed then you can use:

Path.GetFullPath((new Uri(absolute_path)).LocalPath);

This worked.

var s = Path.Combine(@"C:\some\location", @"..\other\file.txt");
s = Path.GetFullPath(s);
string exactPath = Path.GetFullPath(yourRelativePath);

works

This worked for me.

//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);

It`s best way for convert the Relative path to the absolute path!

string absolutePath = System.IO.Path.GetFullPath(relativePath);