Reza on blogging [MVP]

THIS BLOG HAS MOVED TO: http://blogs.devhorizon.com/reza

Subscriptions

<February 2012>
SuMoTuWeThFrSa
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910

News



toronto.sharepoint.camp


Navigation

Post Categories

Other Bloggers

Personal Links

On-the-fly creation of attachments for list items

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();


posted on Friday, August 24, 2007 12:57 AM by rezaa

Powered by Community Server, by Telligent Systems