每次我尝试在我正在进行的项目的电子邮件主体中显示图像时,我都会收到异常。它正在检索共享点图片库中的图像以显示为附件。这是我的代码,我在第264行遇到错误,当前正在调用该方法。
if (txtEventPictureURL.Text != "")
{
string siteurl = "http://it3127:30091";
string filename = txtEventPictureURL.Text;
System.Drawing.Image imgForCallOut = Image.FromStream(GetImageforCharts(siteurl, filename)); //LINE 264 ERROR
mailItem.HTMLBody = Environment.NewLine + @"<html>Event Title : " + txtTitle.Text +
Environment.NewLine + "Event Description : " + txtDescription.Text + Environment.NewLine + "
Event Start Date From :" + dtpStartDate.Text + " To " + dtpEndDate.Text + Environment.NewLine + "Time From : " + cbStartHours.Text + " : " +
cbStartMins.Text + " To " + cbEndHours.Text + " : " + cbEndMins.Text + "Image : " + "<img src=" + imgForCallOut + " /> </html>";
//var doc = global.ThisAddIn.Application.ActiveWindow().WordEditor;
//var pic = doc.Application.Selection.InlineShapes.AddPicture("MY IMAGE URL", true);
//doc.Application.Selection.Hyperlinks.add(pic, "MY URL");
}
}
public static MemoryStream GetImageforCharts(string siteUrl, string fileName)
{
Byte[] fileContentsArray = null;
MemoryStream imageStream = null;
//siteUrl = "http://it3127:30091/";
try
{
using (SPSite site = new SPSite(siteUrl))
// using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
{
SPPictureLibrary chartPictureLibrary = (SPPictureLibrary)web.Lists["Pictures"];
SPQuery query = new SPQuery();
query.Query = @"<Where><Eq><FieldRef Name ='Title'/><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
SPListItemCollection lstImages = chartPictureLibrary.GetItems(query);
foreach (SPListItem r in lstImages)
{
SPFile file = r.File;
using (Stream fileContents = file.OpenBinaryStream())
{
long length = fileContents.Length;
fileContentsArray = new Byte[length];
fileContents.Read(fileContentsArray, 0, Convert.ToInt32(length));
}
}
}
}
imageStream = new MemoryStream(fileContentsArray);
return imageStream;
}
catch (Exception ex)
{
return null;
}
}
}
答案 0 :(得分:0)
正如gzaxx所说,你忽略GetImageforCharts()
内的异常,然后返回null
。
在这种情况下,GetImageforCharts()
在发生异常时不知道该怎么做 - 调用代码要求它发送类型为MemoryStream
的对象,当创建失败时,所有你可以做的是返回null
。
但是不是在那里捕获异常,而是可以从GetImageforCharts()
中删除异常处理程序并在调用代码中捕获它。或者,您可以保留异常处理程序,可以选择记录消息和
throw new ApplicationException("Error getting image for charts", ex);
因此,您可以更好地控制在调用方法时必须捕获的异常。
第三个选项是创建方法
bool TryGetImageforCharts(...params..., out MemoryStream stream)
如果找不到图像,则返回false
(如int.TryParse()
方法)。