• C#取得Web程序和非Web程序的根目录的N种取法


    取得控制台应用程序的根目录方法
    方法1、Environment.CurrentDirectory 取得或设置当前工作目录的完整限定路径
    方法2、AppDomain.CurrentDomain.BaseDirectory 获取基目录,它由程序集冲突解决程序用来探测程序集
    取得WinForm应用程序的根目录方法
    1、Environment.CurrentDirectory.ToString();//获取或设置当前工作目录的完全限定路径
    2、Application.StartupPath.ToString();//获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称
    3、Directory.GetCurrentDirectory();//获取应用程序的当前工作目录
    4、AppDomain.CurrentDomain.BaseDirectory;//获取基目录,它由程序集冲突解决程序用来探测程序集
    5、AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取或设置包含该应用程序的目录的名称
    取得web应用程序的根目录方法
    1.HttpContext.Current.Server.MapPath("~/configs/ChannelUsers.xml")

    HttpContext.Current
    返回当前请求的 HttpContext 对象。如此我们就可以直接访问Request、Response、Session、Application等对象,和Page中访问等同。
    我们无需再将Page用参数的方式传递到我们的类库对象中。

    <DIVCLASS=CODE>HttpContext.Current.Session["name"] = "猪八戒";
    string name = HttpContext.Current.Request.Param["name"];
    HttpContext.Current.Response.Write("猪八戒好吃懒做!");

    <SPANSTYLE="FONT-SIZE: 14pt?="">

    获取网站根目录的方法有几种如:

    Server.MapPath(Request.ServerVariables["PATH_INFO"])
    Server.MapPath("/")
    Server.MapPath("")
    Server.MapPath(".")
    Server.MapPath("../")
    Server.MapPath("..")
    Page.Request.ApplicationPath
    运行结果:
    C:InetpubwwwrootEnglishClubmanageWebForm1.aspx
    C:Inetpubwwwroot
    C:InetpubwwwrootEnglishClubmanage
    C:InetpubwwwrootEnglishClubmanage
    C:InetpubwwwrootEnglishClub
    C:InetpubwwwrootEnglishClub

    以上的方法可以在.aspx中访问,但是如果你在。cs文件就不能用。

    HttpContext.Current.Server.MapPath();
    System.Web.HttpContext.Current.Request.PhysicalApplicationPath   

    在.cs文件中可以用。

    但是HttpContext.Current.Server.MapPath();这个获取的是文件的路径而不是根目录。

    只有System.Web.HttpContext.Current.Request.PhysicalApplicationPath    这个才是获取的根目录,在写获取数据库路径是应该用这个,其他的都有问题。

  • 相关阅读:
    背包问题
    阶乘尾数0的个数
    欧拉筛找素数
    威佐夫博弈
    三角形面积
    deleted
    deleted
    deleted
    deleted
    deleted
  • 原文地址:https://www.cnblogs.com/aaa6818162/p/4666466.html
Copyright © 2020-2023  润新知