I encounter a problem to programmatically create an item into Document Library in SharePoint 2007.
Below is my code fragment, perhaps you might able to point out what is my error:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(_url))
{
using (SPWeb web = site.OpenWeb())
{
SPList customList = web.Lists["Test1"];
foreach (SPListItem ltItem in customList.Items)
{
if (ltItem.Attachments != null && ltItem.Attachments.Count > 0)
{
//Get Test1 File Collection
SPFolder folder = web.GetFolder(ltItem.Attachments.UrlPrefix);
SPFileCollection fileColl = folder.Files;
//Get binary data of attachment
SPFile file = ltItem.ParentList.ParentWeb.GetFile(ltItem.Attachments.UrlPrefix + ltItem.Attachments[0]);
byte[] fileData = file.OpenBinary();
//Get Relative URL of attachment destination
string destFile = fileColl.Folder.Url + "/" + file.Name;
web.AllowUnsafeUpdates = true;
//Add attachment into Document Library
SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test2"];
SPFile file2 = docLib.RootFolder.Files.Add(destFile, fileData, true);
file2.Item.Update();
web.AllowUnsafeUpdates = false;
}
}
}
}
});
I hit "Object reference not set to an instance of an object" at this link of code file2.Item.Update();
Thank you in advanced.
Why do you set the destFile like that? The name of the attachment is enough..
It's only necessary to append the relative URL of the attachement if your requirements say that you need folders, but then you'd create the folders before adding a file to it.