0
点赞
收藏
分享

微信扫一扫

HttpContext.Current.Server.MapPath(““) 未将对象设置到引用的实例异常。

 我根据底部原文的代码进行了升级

web项目没有问题,控制台项目和winform项目有问题,不输出日志

升级原因:

我的项目(控制台和winform)是本地跑的,并且Debug模式,他在读取路径的时候总是会带上“\bin\Debug\”路径,程序找不到文件的真正的所在位置。

重点:

控制台项目和winform项目的根目录就在“\bin\Debug\”下面

 升级后的代码

/// <summary>
/// 获取文件路径
/// </summary>
/// <param name="strPath"></param>
/// <returns></returns>
private 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.TrimStart('\\');
}

string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string _path = "";

#region 过滤 bin和Debug目录
{
string[] str = baseDirectory.Split('\\');

foreach (var item in str)
{
Console.WriteLine(item);
if (item.ToString() != "bin" && item.ToString() != "Debug")
{
_path += $"{item}\\";
}
}
_path = _path.Remove(_path.Length - 1, 1);
}
#endregion

return System.IO.Path.Combine(_path, strPath);
}
}

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

 

 

 

 

 

 


举报

相关推荐

0 条评论