admin管理员组文章数量:1612097
我根据底部原文的代码进行了升级
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);
}
}
原文:https://blog.csdn/yjlwl1213/article/details/30039139
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);
}
}
本文标签: 实例异常对象CurrentHttpContext
版权声明:本文标题:HttpContext.Current.Server.MapPath(““) 未将对象设置到引用的实例异常。 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1728628334a1166783.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论