Thursday, January 6, 2011

Issues With Programmatically Attaching Multiple Files To A List Item

Recently one of my team member was facing issue while adding multiple files to a list item programmatically. The issue was, about 10% files added programmatically were corrupt while uploading. So whenever the user tries to download the file, they were getting "HTTP 500 Internal Server". Below is the piece of code he was using;

HttpFileCollection uploads = HttpContext.Current.Request.Files;


for (int i = 0; i < uploads.Count; i++)

{


HttpPostedFile upload = uploads[i];


if (upload.ContentLength == 0)


continue;


Stream inputStream = upload.InputStream;


byte[] buffer = new byte[inputStream.Length];


inputStream.Read(buffer, 0, (int)inputStream.Length);


inputStream.Close();


eItem.Attachments.Add(upload.FileName, buffer);


}


eItem.Update();
 
On analysing we found out that, the issue was with Attachments.Add method. It was causing some corruptions in the bytes uploaded. So we tried with Attachments.AddNow..
Bingo!!! It started to work without any issues.
 
The only difference between "Attachments.Add" and "Attachments.AddNow" was, "Attachments.AddNow"; it will create new version whenever you attach.
Also, "Attachments.AddNow" internally calls the "Update" method of the List Item. Though its very weird, it is solving the problem of bytes corruption while uploading multiple attachments to the list item.