Home > MOSS 2007 > On-the-fly creation of attachments for list items

On-the-fly creation of attachments for list items

August 23rd, 2007 Leave a comment Go to comments

Here is the code to add an item to a list (task list in this example) programmatically and create and attach a file on the fly. You basically need to encode a set of characters into a sequence of bytes (byte array) and call SPAttachmentCollection.Add method to add the binary representation of your attachment to the list item.

StringBuilder sbLog = new StringBuilder();

sbLog.Append(“Accessing root web of the site collection…\n”);
SPWeb web = new SPSite(“http://moss:21165”).OpenWeb();

sbLog.Append(“Accessing Task list in the root web…\n”);
SPList taskList = web.Lists[“Tasks”];

sbLog.Append(“Adding a new task item…\n”);
SPListItem newTask = taskList.Items.Add();

sbLog.Append(“Populating the fields…\n”);
newTask[“Title”] = “Work hard ,but play harder”;
newTask[“Due Date”] = DateTime.Now;
newTask[“Priority”] = “(1) High”;

sbLog.Append(“Creating the attachment…\n”);
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] bytFile = encoder.GetBytes(sbLog.ToString());
newTask.Attachments.Add(“log.txt”, bytFile);
newTask.Update();

Categories: MOSS 2007 Tags:
  1. No comments yet.
You must be logged in to post a comment.