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

  • 相关阅读:
    Python selenium —— 一定要会用selenium的等待,三种等待方式解读
    python3 selenium 切换窗口的几种方法
    转:对UI自动化测试的一些感悟
    Docker
    【转】selenium之 定位以及切换frame
    selenium——键盘操作
    selenium——鼠标事件
    python 读取Excel表格方法
    springboot maven 更新jar包速度慢的问题
    Python3 读写utf-8文本文件
  • 原文地址:https://www.cnblogs.com/saywa3b/p/5828523.html
Copyright © 2011-2022 走看看