在多线程中使用该方法获取目录报错:未将对象设置到引用
#region 上传图片到腾讯
public async Task<Result> UploadImageToWX(string background_pic_url)
{
var _result = new Result();
var token = GetWxGhAuthorizerAccessToken(AbpSession.ShopId);
if (!token.success)
{
_result.Code = ;
_result.Message = token.message;
return _result;
} try
{
var filename = background_pic_url.Substring(background_pic_url.LastIndexOf('/'));
if (filename.LastIndexOf('.') < )
{
_result.Code = ;
_result.Message = "图片错误";
return _result;
}
var suffix = filename.Substring(filename.LastIndexOf('.')); //报错代码
//string path = System.Web.HttpContext.Current.Server.MapPath("/upload/images/" + DateTime.Now.ToString("yyyyMM")); //解决方案
string path = MapPath("/upload/images/" + DateTime.Now.ToString("yyyyMM")); if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string file = path + "/" + Guid.NewGuid().ToString("n") + suffix; Uri uri = new Uri(background_pic_url);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();//得到图片数据流
Bitmap sourcebm = new Bitmap(resStream);//初始化Bitmap图片
sourcebm.Save(file); var tokenResult = token.data as token_model; var uploadResult = await Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadImgAsync(tokenResult.token, file);
_result.Code = ;
_result.Data = uploadResult;
}
catch (Exception ex)
{ _result.Message = ex.Message; _result.Code = ; } return _result;
}
#endregion
解决方法:
/// <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);
}
}