获取文件路径

一、Web程序(Server.MapPath())

"./" 当前目录
"/" 网站主目录(根目录)
   
../ 上层目录
~/ 网站虚拟目录
如果当前的网站目录为E:\publish\progressbar\
应用程序虚拟目录为E:\publish\progressbar\test\
浏览的页面路径为E:\publish\progressbar\test\default.aspx
在default.aspx页面中使用
Server.MapPath("./")    返回路径为:E:\publish\progressbar\test\
Server.MapPath("/")     返回路径为:E:\publish\progressbar\
Server.MapPath("../")   返回路径为:E:\publish\progressbar\
Server.MapPath("~/")   返回路径为:E:\publish\progressbar\
Server.MapPath("")      返回路径为:E:\publish\progressbar\test
Server.MapPath(".")     返回路径为:E:\publish\progressbar\test
Server.MapPath("~")    返回路径为:E:\publish\progressbar\

在多线程里面使用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);
        }
    }

posted @ 2011-05-24 14:06  Jim哥  阅读(321)  评论(0)    收藏  举报