ASP.NET教程:絕對路徑與相對路徑的拼合方法

來源:互聯網
上載者:User

引言

在做檔案路徑處理時,經常需要對一個路徑的相對路徑進行操作,那麼如何拼合相對路徑以產生新的絕對路徑呢?

Path.Combine()方法

我們知道System.IO.Path是專門用來處理路徑的靜態類,它有一個Combine()方法就是用於拼接路徑的,我們來測試一下其拼接效果。

我們使用一個命令列程式進行測試,這裡要測試相對於檔案C:abc123avatar.html的一系列相對路徑,測試代碼如下:

class Program

{

static string path = @"C:abc123avatar.html";

static void Main(string[] args)

{

Console.WriteLine(path);

Console.WriteLine("輸入相對路徑以完成合併:");

Console.WriteLine();

while (true)

{

Console.WriteLine("合并為:"+合并路徑(Console.ReadLine()));

Console.WriteLine();

}

}

private static string 合并路徑(string p)

{

return Path.Combine(Path.GetDirectoryName(path), p);

}

}

其中“合并路徑”方法的功能是先擷取檔案的所在目錄,再與相對路徑拼合。

測試結果:

可以看到,常規的路徑拼合沒有問題,但是輸入“..”就沒有被正確處理為上級目錄,而是直接進行了合并,這不是我期望看到的。

怎樣做才能支援“..”形式的相對路徑呢?

利用Uri對象的建構函式

我發現Uri對象在構造時可以傳入一個基於的Uri及一個相對路徑以構造為新的Uri,而我們可以以“file://……”的形式來表示本地檔案路徑,讓我們改動一下代碼,進行一下相對Uri的拼合測試。

改動後的代碼:

class Program

{

//static string path = @"C:abc123avatar.html";

static string path = @"file:///C:/abc/123/avatar.html";

static void Main(string[] args)

{

Console.WriteLine(path);

Console.WriteLine("輸入相對路徑以完成合併:");

Console.WriteLine();

while (true)

{

//Console.WriteLine("合并為:" + 合并路徑(Console.ReadLine()));

Console.WriteLine("合并為:" + 合并Uri(Console.ReadLine()));

Console.WriteLine();

}

}

private static string 合并路徑(string p)

{

return Path.Combine(Path.GetDirectoryName(path), p);

}

private static string 合并Uri(string p)

{

return new Uri(new Uri(path), p).AbsoluteUri;

}

}

測試結果:

好極了,完美支援“../”形式的相對路徑!

完善

那麼接下來的工作就是將路徑轉換為Uri形式,然後拼合相對路徑,再轉換迴路徑形式就可以了。

轉換的時候僅僅是採取字串處理的方法,改動後的代碼如下:

class Program

{

static string path = @"C:abc123avatar.html";

static void Main(string[] args)

{

Console.WriteLine(path);

Console.WriteLine("輸入相對路徑以完成合併:");

Console.WriteLine();

while (true)

{

Console.WriteLine("合并為:" + 合并路徑(Console.ReadLine()));

Console.WriteLine();

}

}

private static string 合并路徑(string p)

{

return new Uri(new Uri("file:///" + path.Replace("\", "/")), p.Replace("\", "/")).AbsoluteUri.Substring(8).Replace("/", "\");

}

}

測試結果:

結語

結果很令人滿意,但我總覺得這是個土方子、山寨辦法,誰有更簡便、正統點的方法嗎?

感謝天方這麼快就提出了正統的寫法:Path.GetFullPath(Path.Combin(@"C:ac","...text"));

我之前找了那麼久,又折騰那麼久,才弄出個山寨的來,實在汗顏啊,呵呵。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.