zoukankan      html  css  js  c++  java
  • .net 获取网站根目录总结

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

     

    复制代码
      Server.MapPath(Request.ServerVariables["PATH_INFO"])    //页面详细路
      Server.MapPath("/")   //根目录
      Server.MapPath("")        //当前代码文件所在的目录路径   
      Server.MapPath(".")   
      Server.MapPath("../") //当前代码所在路径的上级路径  
      Server.MapPath("..") 
        Page.Request.ApplicationPath 
    复制代码

     

     

    以上的代码在"http://localhost/EnglishClub/manage/WebForm1.aspx" 页面运行结果: 

     

    复制代码
    C:InetpubwwwrootEnglishClubmanageWebForm1.aspx  
    C:Inetpubwwwroot  
    C:InetpubwwwrootEnglishClubmanage  
    C:InetpubwwwrootEnglishClubmanage  
    C:InetpubwwwrootEnglishClub  
    C:InetpubwwwrootEnglishClub
    /
    复制代码

     

     

     

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

    下面两个都可以在.cs文件中用:

     

    HttpContext.Current.Server.MapPath();//所在文件夹路径
    System.Web.HttpContext.Current.Request.PhysicalApplicationPat;//根路径

     

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

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

    System.Web.HttpContext.Current.Request.PhysicalApplicationPath和Server.MapPath("~/")效果是一样的。

    Server.MapPath("~/");//无论代码所在的文件的、页面路径是什么,永远返回 C:InetpubwwwrootEnglishClub(就是当前程序运行的所在根目录)

    如果存储附件的路径到数据库的话,不应该把绝对路径存进去。应该只存储 文件名部分。

    例如:/uploads/abc.txt

    当需要浏览文件的时候,在在读取出来的路径:(即/uploads/abc.txt),前面+网站的路径:例如:http://abc.com+"/uploads/abc.txt"

     

     

    二.线程中获取系统路径

        以上都是在web程序引用下获取路径,

    在多线程里面使用HttpContext.Current,HttpContext.Current是得到null的. 

    所以以上方法在线程中直接使用是不行的。

    在线程中得到系统根路径可以用此方法:

     

    复制代码
            public static string MapPath(string strPath) 
            { 
                if (HttpContext.Current != null) 
                { 
                    return HttpContext.Current.Server.MapPath(strPath); 
                } 
                else //非web程序引用 
                { 
                    strPath = strPath.Replace("/", "\"); 
                    if (strPath.StartsWith("\")) 
                    { 
                        //strPath = strPath.Substring(strPath.IndexOf('\', 1)).TrimStart('\'); 
                        strPath = strPath.TrimStart('\'); 
                    } 
                    return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath); 
                } 
            } 
    复制代码

     

  • 相关阅读:
    [leetcode]Combination SumII
    NSum小结
    image 与 canvas 的相互转化
    $_SERVER 相关变量
    最近做的项目,总结一下。
    开始在博客园,写博客,先写点东西。
    Codeforces Round #584 C. Paint the Digits
    Codeforces Round #584 B. Koala and Lights
    Codeforces Round #584 A. Paint the Numbers
    HDU-2296-Ring(AC自动机, DP)
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/5390264.html
Copyright © 2011-2022 走看看