C# 如何獲取當前應用程序的上一級路徑


用法:

1.Server.MapPath ("/") 應用程序根目錄所在的位置 如 C:\Inetpub\wwwroot\

2.Server.MapPath ("./") 表示所在頁面的當前目錄

注:等價於Server.MapPath ("") 返回 Server.MapPath ("")所在頁面的物理文件路徑

3.Server.MapPath ("../")表示上一級目錄

4.Server.MapPath ("~/")表示當前應用級程序的目錄,如果是根目錄,就是根目錄,如果是虛擬目錄,就是虛擬目錄所在的位置

如:C:\Inetpub\wwwroot\Example\ 注:等效於Server.MapPath ("~")。

 

但是, 有些時候, 我們需要獲取根目錄以上的路徑, 這時候該腫么辦? 

 

下面 提出兩種解決方案。

第一種是 

C#的path.GetFullPath 獲取上級目錄實現方法

string path = new directoryinfo("../").fullname;//當前應用程序路徑的上級目錄

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.io;
namespace pathtest
{
class program
{
static void main(string[] args)
{
//使用appdomain獲取當前應用程序集的執行目錄
string dir = appdomain.currentdomain.basedirectory;
string info = string.format("appdomain方法獲取當前程序集目錄:{0}", dir);
console.writeline(info);
//使用path獲取當前應用程序集的執行的上級目錄
dir = path.getfullpath("..");
info = string.format("path方法獲取當前程序集上級目錄:{0}", dir); (www.jb51.net)
console.writeline(info);
//使用path獲取當前應用程序集的執行目錄的上級的上級目錄
dir = path.getfullpath(@"....");
info = string.format("path方法獲取當前程序集目錄的級的上級目錄:{0}", dir);
console.writeline(info);
//使用path獲取當前應用程序集的執行目錄的上級目錄
dir = path.getfullpath(@"......");
info = string.format("path方法獲取當前程序集目錄的上級目錄的上級目錄:{0}", dir);
console.writeline(info);
//在當前程序集目錄中添加指定目錄
dir = path.getfullpath(@"io");
info = string.format("在當前程序集目錄中添加指定目錄:{0}", dir);
console.writeline(info);
console.read();
}
}
}

 

這種情況, 不是常有效, 腫么辦呢? 我們可以采取靈活一點的辦法, 下面介紹靈活一點的辦法。

 

不僅僅可以針對上級目錄的問題, 還可以靈活的處理許多類似的問題,  多謝一位前輩對我的指點~ 

 

第二種做法的思路是這樣:

 

首先獲取應用程序的根目錄, 

string root = System.Web.HttpContext.Current.Server.MapPath("~/");

 

再用數組,把 "\\" 作為分隔符, 區別開來
string[] temp = root.Split("\\".ToCharArray());

 

遍歷得到的數組
for (int i = 0; i < temp.Length - 2; i++)
{
a += temp[i];
a += "\\";
}

比如獲取上一級, 就把 length -2 , 就可以獲得上一級的目錄

 上上級, 就繼續 減掉 2個, 以此類推。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM