zoukankan      html  css  js  c++  java
  • C# 如何获取当前应用程序的上一级路径

    如我们所常知的那样, Server.MapPath() 属性可以获取应用程序的根目录

    用法:

    1.Server.MapPath ("/") 应用程序根目录所在的位置 如 C:Inetpubwwwroot

    2.Server.MapPath ("./") 表示所在页面的当前目录

    注:等价于Server.MapPath ("") 返回 Server.MapPath ("")所在页面的物理文件路径

    3.Server.MapPath ("../")表示上一级目录

    4.Server.MapPath ("~/")表示当前应用级程序的目录,如果是根目录,就是根目录,如果是虚拟目录,就是虚拟目录所在的位置

    如:C:InetpubwwwrootExample 注:等效于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个, 以此类推。

    就说这么多了, 希望对大家有所帮助~ 

  • 相关阅读:
    面向对象、构造函数的区别
    写一个function,清除字符串前后的空格。(兼容所有浏览器)
    两个DIV高度自适应方法(左右两个DIV高度一样)
    js数组去重
    input框处理删除小图标的功能
    查找显示高亮
    JSON.parse()和JSON.stringify()
    jquery封装
    怎么理解HTML语义化
    html5语义化标签
  • 原文地址:https://www.cnblogs.com/29boke/p/5828342.html
Copyright © 2011-2022 走看看