C# 如何获取当前应用程序的上一级路径 Server.MapPath 的使用方法 C#的path.GetFullPath 获取上级目录实现方法

用法: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

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个, 以此类推。

相关文章
相关标签/搜索