Adding an attachment to a SharePoint list item programmatically

I needed a way to upload an attachment to a list item within an Event Handler but discovered it was not that simple. Now that I have the code to add attachment to a list item, I don’t want to lose it.

The following code can be called from a web part or an application page easily. What was complicated for me was trying to attach a file from the ItemAdding/ItemAdded Event Handler.

This code snippet can be added to a web part or an application page, or even in the ItemAdded/ItemAdding event handler:

Stream fStream;
string fileName = string.Empty;
byte[] contents;
if (context != null) {
    if (context.Request.Files.Count > 0) {
	try {
	    HttpFileCollection aFiles = context.Request.Files;
	    for (int i = 0; i < aFiles.Count; i++) {
		HttpPostedFile userFile = aFiles[i];
		fileName = userFile.FileName.Substring(3);

		fStream = userFile.InputStream;
		contents = new byte[fStream.Length];
		fStream.Position = 0;

		fStream.Read(contents, 0, (int)fStream.Length);
		fStream.Close();

		itemToAdd.Attachments.Add(fileName, contents);
		itemToAdd.SystemUpdate();
	    }

	} catch (Exception ex) {
	    //LogEventError
	}
    } else {
	//
    }
}

Hope this helps.

.advertisement

Leave a Reply