Server.MapPath相关

本文详细解释了在ASP.NET中使用Server.MapPath的方法,包括如何获取服务器上的物理路径,以及在多线程环境下的使用技巧。同时,提供了解决非web程序引用时的问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果你从Page类继承的类中执行这条语句,才可以简单地使用 
DataBase = Server.MapPath("data.mdb");
否则写全命名空间:System.Web.HttpContext.Current.Server.MapPath();

总注:Server.MapPath获得的路径都是服务器上的物理路径,也就是常说的绝对路径
1、Server.MapPath("/")
注:获得应用程序根目录所在的位置,如 C:\Inetpub\wwwroot\。
2、Server.MapPath("./")
注:获得所在页面的当前目录,等价于Server.MapPath("")。
3、Server.MapPath("../")
注:获得所在页面的上级目录。
4、Server.MapPath("~/")
注:获得当前应用级程序的目录,如果是根目录,就是根目录,如果是虚拟目录,就是虚拟目录所在的位置,如C:\Inetpub\wwwroot\Example\。

在多线程里面使用HttpContext.Current,HttpContext.Current是得到null的. 
所以在线程调用方法,方法中类里面的System.Web.HttpContext.Current.Server.MapPath() 获取不到对象。

应该这样用:

    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);
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值