Saturday, June 2, 2012

Insert new item with attachment to sharepoint list programmatically


Here is steps to add new item with attachment to sharepoint list programmatically.

- Get name of the file
string _Str_File_Name = fuAttachment.PostedFile.FileName;

- Get stream data by following way
byte[] contents = GetFileStream();

- Declare variable which hold the newly created item id.
int _Int_ID = 0;

- Follow the steps to insert new item into your sharepoint list with attachment.

- Create new instance of site with your current application
using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
{

- Create new web instance and open web for current application
using (SPWeb web = site.OpenWeb())
{

- Create new list object and get your list
SPList list = web.Lists["Your List Name"];

- Set allowunsafeupdates for web & site to true
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;

- Create new list item object and add new item for newly created list object
SPListItem item = list.Items.Add();

- Assign value for newly created item
item["Title"] = "Title1";

- Assign selected filename and stream data
if (!string.IsNullOrEmpty(_Str_File_Name != null) && (contents.Length > 0))
{
SPAttachmentCollection fileAttach = item.Attachments;
fileAttach.Add(_Str_File_Name, contents );
}


- Update item which will add new item to list
item.Update();

- if you want to manipulate on newly created item then you can get id of the newly created item by following way
itemId = item.ID;
}
}

- Convert your selected file to byte by following function
private byte[] GetFileStream()
{
//fuAttachment is your file select control
if (!fuAttachment.HasFile)
return null;
Stream fStream = fuAttachment.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
return contents;
}
Click Insert new item to sharepoint list programmatically to view my previous post to add item to sharepoint list.

-That’s it for adding new item to your sharepoint list with attachment.

No comments:

Post a Comment