MapPath 终极版

// <summary>
/// Maps a virtual path to a physical disk path.
/// </summary>
/// <param name="path">The path to map. E.g. "~/bin"</param>
 /// <returns>The physical path. E.g. "c:\inetpub\wwwroot\bin"</returns>
 public virtual string MapPath(string path)
{
     if (HostingEnvironment.IsHosted)
      {
       //hosted
         return HostingEnvironment.MapPath(path);
     }

   //not hosted. For example, run in unit tests
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
            return Path.Combine(baseDirectory, path);
        }

 

避免了 HttpContext.Current 为Null 的问题。