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

    用法:

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

  • 相关阅读:
    HUE配置文件hue.ini 的impala模块详解(图文详解)(分HA集群)
    poj 1815 Friendship (最小割+拆点+枚举)
    Android项目中包名的改动
    Android MediaPlayer Error -1004
    hive原生和复合类型的数据载入和使用
    Linux学习笔记之权限与命令之间的关系(重要)及文件与文件夹知识总结
    kafka集群搭建与apiclient创建
    Android中各种Adapter的使用方法
    【从零学习Python】Ubuntu14.10下Python开发环境配置
    leetcode
  • 原文地址:https://www.cnblogs.com/saywa3b/p/5828523.html
Copyright © 2011-2022 走看看