System.Web.HttpContext.Current.Server.MapPath("/") 这个常用来表示网站的根目录,偶尔出现“未将对象设置到引用实例”的异常。
用一个折中的方法:
/// <summary>
/// 获取文件路径
/// </summary>
/// <param name="strPath"></param>
/// <returns></returns>
private string MapPath(string strPath)
{
if (HttpContext.Current != null)
{
return HttpContext.Current.Server.MapPath(strPath);
}
else //非web程序引用
{
strPath = strPath.Replace("/", "\\");
if (strPath.StartsWith("\\"))
{
strPath = strPath.TrimStart('\\');
}
return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
}
}