用法:css
1.Server.MapPath ("/") 應用程序根目錄所在的位置 如 C:\Inetpub\wwwroot\html
2.Server.MapPath ("./") 表示所在頁面的當前目錄數組
注:等價於Server.MapPath ("") 返回 Server.MapPath ("")所在頁面的物理文件路徑app
3.Server.MapPath ("../")表示上一級目錄dom
4.Server.MapPath ("~/")表示當前應用級程序的目錄,若是是根目錄,就是根目錄,若是是虛擬目錄,就是虛擬目錄所在的位置post
如:C:\Inetpub\wwwroot\Example\ 注:等效於Server.MapPath ("~")。url
可是, 有些時候, 咱們須要獲取根目錄以上的路徑, 這時候該腫麼辦? spa
下面 提出兩種解決方案。.net
第一種是 orm
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個, 以此類推。