I am creating new web in the ItemAdded event receiver and I want to upload the picture that is attached with the item to the newly created site's picture library and if no attachment is there then I want to upload the Sharepoint's blank image file which has the path. _layouts/15/images/256_icgen.png
My code is:
newWeb = properties.Web.Webs.Add(url, url, desc, 1033, Webs.Community.WebTemplate, true, false);
newWeb.Lists.Add("CommunityPicture", string.Empty, SPListTemplateType.PictureLibrary);
newWeb.Update();
if (item.Attachments.Count > 0)
{
string attachUrl = SPUrlUtility.CombineUrl(item.Attachments.UrlPrefix, "/" + item.Attachments[0]);
string fileName=StoreAttachmentToPicLib(attachUrl,properties.Web,newWeb);
item.Attachments.Delete(fileName);
item.Update();
}
else
{
string attachUrl = "_layouts/15/images/256_icgen.png";
string fileName = StoreAttachmentToPicLib(attachUrl, properties.Web, newWeb);
}
private string StoreAttachmentToPicLib(string attachUrl,SPWeb ListWeb,SPWeb newWeb)
{
//List web is All Communities web which will refer to communities list and the newWeb is the subsite of community.
SPFile oFile = ListWeb.GetFile(attachUrl);
string fileName = oFile.Name;
byte[] binFile = oFile.OpenBinary(); // error comes here "Cannot open file"
SPFolder library = newWeb.Folders["CommunityPicture"];
library.Files.Add("HomePic.jpg", binFile, true);
library.Update();
return fileName;
}
My problem is that I the file oFile
is found successfully but when the control reaches to OpenBinary() error is thrown.
Am I going through right way or what am I missing in my code?