SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("http://br-pc-203/"))
{
SPList customList = site.RootWeb.Lists["Custom List"];
SPList documentLibrary = site.RootWeb.Lists["Document Library"];
SPFolder folder = site.RootWeb.Folders[documentLibrary.Title];
SPFileCollection fileCollection = null;
foreach (SPListItem ltItem in customList.Items)
{
if (ltItem.Attachments != null && ltItem.Attachments.Count > 0)
{
foreach (String sFilename in ltItem.Attachments)
{
fileCollection = folder.Files;
SPListItem docItem = documentLibrary.Items.Add();
SPFile attachmentFile = ltItem.ParentList.ParentWeb.GetFile(ltItem.Attachments.UrlPrefix + sFilename);
string destFile = fileCollection.Folder.Url + "/" + attachmentFile.Name;
byte[] fileData = attachmentFile.OpenBinary();
SPFile addedFile = fileCollection.Add(destFile, fileData, site.RootWeb.CurrentUser, site.RootWeb.CurrentUser, Convert.ToDateTime(ltItem[SPBuiltInFieldId.Created]), Convert.ToDateTime(ltItem[SPBuiltInFieldId.Modified]));
SPListItem item = addedFile.Item;
item[SPBuiltInFieldId.Created] = Convert.ToDateTime(ltItem[SPBuiltInFieldId.Created]);
item[SPBuiltInFieldId.Modified] = Convert.ToDateTime(ltItem[SPBuiltInFieldId.Modified]);
addedFile.Item.Update();
}
}
}
}
});