Tuesday, September 9, 2008

Programmatically uploading an attachment to a list item in WSS3/MOSS 2007

If you need to upload a file into a SharePoint document library through code following code is helpful.

SPList list = web.Lists["MyList"];
if (list != null)
{
web.AllowUnsafeUpdates = true;
SPListItem item = list.Items.Add();
item["Title"] = "my title";

if (fileAttachment.PostedFile != null && fileAttachment.HasFile)
{
Stream fStream = fileAttachment.PostedFile.InputStream;

byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
fStream.Dispose();

SPAttachmentCollection attachments = item.Attachments;
string fileName = Path.GetFileName(fileAttachment.PostedFile.FileName);
attachments.Add(fileName, contents);

}

item.Update();
web.AllowUnsafeUpdates = false;

}