In this article I am going to show how you can Add/Edit/Read
SharePoint task attachment programmatically. Here is the sample code;
Save Attachment
bool saveAttachments(string attachFilePath, string list, int taskID)
{try{using (SPWeb web = site.OpenWeb()){SPList Selectedlist = web.Lists[list];SPListItem itemToUpdate = Selectedlist.GetItemById(taskID);FileStream stream = new FileStream(@attachFilePath, ileMode.Open);byte[] byteArray = new byte[stream.Length];stream.Read(byteArray, 0, Convert.ToInt32(stream.Length));stream.Close();itemToUpdate.Attachments.Add(attachFile, byteArray);itemToUpdate.Update();return true;}}catch (Exception ex){MessageBox.Show("Couldn't save the attachment" + Environment.NewLine + ex.Message, "Message");return false;}}
Remove Attachment
private void btnremoveAttach_Click(object sender, EventArgs e){try{if (dataGridViewAttachments.CurrentRow != null){DialogResult dr = MessageBox.Show("Are you sure to delete the attachment?", "Message", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);if (dr == System.Windows.Forms.DialogResult.Yes){string name = dataGridViewAttachments.CurrentRow.Cells["Attachments"].Value.ToString();using (SPWeb web = site.OpenWeb()){SPList Selectedlist = web.Lists[list];SPListItem item = Selectedlist.GetItemById(taskID);SPAttachmentCollection AttachmentCollection = item.Attachments;item.Attachments.Delete(name);item.Update();}}}}catch (Exception ex){MessageBox.Show("Couldn't delete the attachment." + Environment.NewLine + ex.Message, "Message");return ;}}
Read Attachment
bool GetAttachments(string attachFilePath, string list, int taskID)
{try{ sing (SPWeb web = site.OpenWeb()){SPList Selectedlist = web.Lists[list];SPListItem item = Selectedlist.GetItemById(taskID); SPAttachmentCollection AttachmentCollection = item.Attachments;if (AttachmentCollection.Count > 0){SPFolder folder = web.Folders["Lists"].SubFolders[list].SubFolders["Attachments"].SubFolders[item.ID.ToString()];foreach (SPFile file in folder.Files){DataRow dr = dtAttachment.NewRow();dr["Name"] = file.Name;dtAttachment.Rows.Add(dr);}}}}catch (Exception ex){MessageBox.Show("Couldn't read the attachment details" + Environment.NewLine + ex.Message, "Message");return false;}
Ok - this post was never read. The code for Read Attachments is the same for Save?
ReplyDeleteThanks Andrea Vasapollo..
DeleteI have changed it.
Hi,
DeleteI need the code to read the content from the document in the sharepoint library, i have read few article where we have to use Open XMl SDK dll, i need code withour using this SDK,
Thanks in Advance
Vinay
Yeah!! SMS Attachments has enabled business organizations to share files, brochures, and menus through SMS just the way they did it with an email. Contact us: +91-8349217770 or Sales@Msgclub.Net / Sales@smsprovider.com
ReplyDelete