Programmatically(C#) Adding, Deleting, Copying and Downloading Attachments in SPList

…m back !!!

I had not expected that I’ll be back like this.. I wanted to be back with a lot of good stuff to be shared.. But today I m here just to spend time in someone’s company… I m desperately looking for somebody whom I can talk to…somebody who responds me back…
I am into that typical state of mind where I am more than lonely…rather dying of these irritating and pissing off surroundings.. And my bad luck that despite the many good ppl in my life I have absolutely nobody around me at present…Everybody is so busy that they can’t lend me an ear for even a little time… Hence I decided to talk to the world (and no particular busy soul)..

As I said in my previous posts, I have a lot to do……… too many xams on my way (for which I have studied almost nothing) and a lot of work in office (which is the only thing I am loving these days)… Yup… m loving to spend time in office… in fact I hardly feel like going home… Each day on my way back home I m more stressed with the idea of spending time in a place so unfamiliar, with ppl so unfriendly and irritatingly unhygeinic, be it is physically or mentally… !!!

I hate my time within those four walls of the PG where I stay… I really count upon each minute to pass by for the day when I can have a small house of my own… A place where everything is intimately attached with me… A place where ppl whom I love rather who are my own will dwell…

All this while the worst thing that happened in my life is the change of my mindset owing to the conditions I was put into from time to time………
I always believed that regionalism and kinda stuff is all nonsense but now I understand it when I have developed this bitter hatred towards the ppl of on of the states in my own country….
I still try not to believe that everybody from this region is a jerk but my experiences force me to do so………. Apologies !!!

I developed a new functionality in my application where I worked with attachments (i crave for this word in my life) in SharePoint Lists programmatically… It was a nice learning… Let me share my experiences with that too………… And now I seem to have found an informative stuff for my readers and an apt title too….(sorry for the cribbing above)…….

**********************************************************************

ADDING AN ATTACHMENT TO AN ITEM IN SPLIST :

private void AddNewAttachment(int NodeID)
{
try
{
SPList myList = SPContext.Current.Web.Lists["Item List"];
SPListItem myNewItem = myList.GetItemById(NodeID);

if (fileUpload.PostedFile != null && fileUpload.HasFile)
{
Stream fStream = fileUpload.PostedFile.InputStream;

byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
fStream.Dispose();

SPAttachmentCollection attachments = myNewItem.Attachments;
string fileName = Path.GetFileName(fileUpload.PostedFile.FileName);
attachments.Add(fileName, contents);

myNewItem["Attached FileName"] = fileName; // store the name of the file in a column for future requirements
myNewItem.Update();
}
}
catch (Exception eAdd)
{
string errAdd = eAdd.Message;
}
}
 

DELETING AN ATTACHMENT FROM SPLIST :

private void DeleteAttachment(int NodeID)
{
try
{
SPList myList = SPContext.Current.Web.Lists["Item List"];
SPListItem delItem = myList.GetItemById(NodeID);
SPAttachmentCollection atCol = delItem.Attachments;
if (delItem["Attached FileName"] != null)
{
string strFileName = delItem["Attached FileName"].ToString();
delItem["Attached FileName"] = string.Empty;
atCol.Delete(strFileName);
delItem.Update();
}
}
catch (Exception eDel)
{
string errDel = eDel.Message;
}
}

DOWNLOADING THE ATTACHMENT :

Find the download link first then reedirect to another aspx page so that the response ending on the current page does not affect the functionalities on this :-

private void DownloadAttachment(int NodeID)
{
try
{
string AttachmentURL = string.Empty;
SPList myList = SPContext.Current.Web.Lists["Item List"];
SPListItem attItem = myList.GetItemById(NodeID);
if (attItem["Attached FileName"] != null)
{
AttachmentURL = “/Lists/Item%20List1/Attachments/” + NodeID.ToString() + “/” + attItem["Attached FileName"].ToString();

System.Web.HttpContext.Current.Session["FileName"] = attItem["Attached FileName"].ToString();
System.Web.HttpContext.Current.Session["Attachment"] = AttachmentURL.Trim();
}
else
{
lblReport.Text = GetMessage(110);
}
if (AttachmentURL != string.Empty)
Page.Response.Write(“”);
}
catch (Exception eDwn)
{
string errDwn = eDwn.Message;
}
}
At the aspx page you need to run the code as :

if(System.Web.HttpContext.Current.Session["Attachment"] != null)
{
string strName = System.Web.HttpContext.Current.Session["FileName"].ToString();
string sbURL = System.Web.HttpContext.Current.Session["Attachment"].ToString();
System.Web.HttpResponse response;
response = System.Web.HttpContext.Current.Response;
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
response.AppendHeader(“Content-disposition”, “attachment; filename=” + strName);
response.AppendHeader(“Pragma”, “cache”);
response.AppendHeader(“Cache-control”, “private”);
response.Redirect(sbURL);
response.End();
}

Now set these sessions to null.

COPYING AN ATTACHMENT FROM ONE ITEM TO ANOTHER IN SPLIST :

private void CopyAttachment(int FromID, int NodeID, string AttachedFile)
{
try
{
SPList myList = SPContext.Current.Web.ParentWeb.Lists["Item List"];
SPListItem myItem = myList.GetItemById(NodeID);
SPListItem myPrevItem = myList.GetItemById(FromID);

SPAttachmentCollection attColl = myPrevItem.Attachments;

SPFile attFile = myPrevItem.ParentList.ParentWeb.GetFile(myPrevItem.Attachments.UrlPrefix + AttachedFile);
string fileRead = myPrevItem.Attachments.UrlPrefix.ToString() + AttachedFile;

StreamReader fsReader = new StreamReader(attFile.OpenBinaryStream());
Stream fStream = fsReader.BaseStream;

byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
fStream.Dispose();

myItem.Attachments.Add(AttachedFile, contents);
myItem.Update();
}
catch (Exception eCopy)
{
string errCopy = eCopy.Message;
}

}

*********************************************************************

I will be regular with my findings again…

Somehow I am feeling better now like yesterday when I drenched myself in the first rains of the season to forget the whole world…

Last but not the least a really thoughtful quote from Calvin:

Why did evolution give us something like a sense of humour? Because if we couldn’t laugh at things that didn’t make sense, we wouldn’t be able to react to most part of life.

About these ads

~ by Neha Sinha on May 23, 2008.

33 Responses to “Programmatically(C#) Adding, Deleting, Copying and Downloading Attachments in SPList”

  1. Hi there Neha,
    I’m trying to get the the “Adding an Attachment” code to work (which I owe you thanks for writing!). My problem is that I don’t have the ID, I have the name of the item.

    Code:
    try
    {
    SPList oList = SPContext.Current.Web.Lists["ContractInformation"];
    currentForm = Request["record"].ToString();

    //SPListItem oListItem = oList.Items[currentForm];
    SPListItem oListItem = oList.GetItemById(currentForm);

    end code:

    Isn’t there a better way? Like: SPListItem oListItem = oList.GetItemByDisplayName(currentForm)??? without having to loop through the entire list?

    Thanks for your help.

  2. @DT : Hi Darren,

    Every item/record that gets added to the SPList gets an ID by default. You can see this ID by adding the ID column to the List View. If at all you need to access the record by its name then a better way is to use the CAML Query for this.

    For e.g. You can have a CAML Query something similar to ~

    SPQuery myQuery = new SPQuery();
    string Querycolumn = “Title”;
    myQuery.Query = “” + “recordNAME” + “”;

    SPList myList = SPContext.Current.Web.Lists["LIST NAME"];

    SPListItemCollection myColl = myList.GetItems(myQuery);

    Now this Item Collection will include all the relevant records.

  3. hey neha…
    Im trying to make my Splist read only… basically trying to freeze it.. so that the rows cannot be edited… do you have a solution for this….

  4. @Nidhi : Go to the Advanced Settings on the List Settings page.
    Select ‘None’ against the Edit Access settings.
    You can set item level permissions via Advanced Settings.

  5. HI Neha,
    Thanks for your codes it has really helped me. I got another problem , I have to update an attachment found in a list which I have just copied, that is if the source attachment is updated the destination attachment must also be updated. Is it feasible to do it via coding?

  6. @Kunal : The source of the attachment may be present anywhere on your work environmet. SPList does not maintain the source reference/location. Hence it is not possible to update the changes for an attachment via coding.

    On a different note : If you have two Sharepoint portals respectively on a development and a production environment, you can very well update the changes done on the dev site to the production environment using Content Deployment. This works in case of list item attachments as well.

  7. Thx very much :)

  8. Hi Neha –

    I’m having a problem deleting an attachment. I get an error saying attachment field cannot be updated.

    SPListItem delItem;
    SPAttachmentCollection atCol;

    delItem = listCopyCenter.GetItemById(Convert.ToInt32(item));
    atCol = delItem.Attachments;
    if (delItem["Attachments"] != null)
    {
    string strFileName = delItem["Attachments"].ToString();
    delItem["Attachments"] = string.Empty; //error on this line
    atCol.Delete(strFileName);
    delItem.Update();
    }

    Thanks!

  9. Your post was very useful for me.

    And the first few paragrapgs has given a line of thought too..

    Thanks a ton!

  10. Thanks Jose !

  11. Code worked beautifully the first time. Thank you for your help. You are a blessing!

  12. Neha – thanks for the post. Just a comment regarding evolution of laughter: I think the mental faculty to laugh and smile evolved to help us live in a society. It serves to diffuse difficult situations that arise in our community, and also acts as a way to glue members of a group together.

  13. Hi Neha,
    Actually I want to download a file from sharepoint server but using web services. Is there any method to do so?(using web services specifically). Somehow I am able to upload files to sharepoint server but the file contents are not properly reflected. I am totally new to Sharepoint. Can you please suggest any possible outcome?
    Thanks in Advance.
    Regards,
    Hitesh

  14. Thank you so much for posting this code on adding an attachment. Nice to have some “wheel inventors” for those of us who couldn’t possibly re-invent.

  15. how to get the attachment size in mb or kb

  16. Sure version :)

  17. hey neha…i have a query changes made to my attachment file be recorded in version history…reply awaited thakursahil@in.com

  18. hello there,

    you article is very good.I want same like this.but here you mentioned nodeID.What is nodeID?, ho can i get nodeID?

  19. Greetings,

    I am very beginner in moss2007 programming.. can you please help me

    Issue details :

    I am facing and error while adding an item to a list programetically only while executed without debug mode else I am able to insert perfectly.

    Error Code “there is no web named (“/sites/mosscollab/”)

    code here
    Dim objspsite As New SPSite(“http://moss2007chp03″)
    Dim objspcoll As SPWeb = objspsite.AllWebs(“/sites/mosscollab/”)
    Dim objlstcoll As SPListItemCollection = objspcoll.Lists(“Parts List”).Items()
    Dim objattachcoll As SPAttachmentCollection
    ‘check whether the title already exists or not
    For Each temp As SPListItem In objlstcoll
    If (temp(“Title”).ToString.ToLower() = txttitle.Text.Trim().ToLower()) Then
    MessageBox.Show(“Title is already exists”)
    Return
    End If
    Next
    Dim lstitem As SPListItem = objlstcoll.Add()
    lstitem(“Title”) = txttitle.Text.Trim()
    lstitem(“Part Number”) = CInt(txtpartno.Value.ToString().Trim())
    lstitem(“Price”) = CInt(txtprice.Value.ToString().Trim())
    ‘upload document
    If (lbldocname.Text.Trim() “”) Then
    Dim destpath As String = lbldocname.Text.Trim()
    ‘freeze cursor
    Cursor = Cursors.WaitCursor
    ‘assign filestream and open for read
    Dim fstream As FileStream = File.OpenRead(lbldocname.Text.Trim())
    ‘define the byte array
    Dim contents(fstream.Length) As Byte
    fstream.Read(contents, 0, fstream.Length)

    fstream.Close()
    objattachcoll = lstitem.Attachments
    objattachcoll.Add(lbldocname.Text.Trim(), contents)
    End If
    lstitem.Update()

  20. Hi Neha,

    How can attachment size be determined ?

  21. hai i want how to rating a document in sharepoint 2007

  22. Maybe you should make changes to the post name Programmatically(C#) Adding, Deleting, Copying and Downloading Attachments in SPList Neha’s… to something more better for your content you create. I enjoyed the post nevertheless.

  23. [...] Programmatically(C#) Adding, Deleting, Copying and Downloading Attachments in SPList May 200819 comments 5 [...]

  24. good post…

  25. Hi,

    Great post, it helps me a lot.

    But i’m having a problem after i upload the file i want to open it directly from sharepoint. When i’m opening a file he tells me that the file is damaged (could not bu correctly decoded)
    Have you any idea what the problem is.

    Thanks

  26. Can u plz share the code how to create list programtically and insert,delete, and download on that list.

    Thanks i m new to sharepoint

  27. Beauty with Brains=Neha Sinha. I will be a regular reader frm now on provided u update something here at least once in a week…:P..

    • Yup… keeping this space updated is on my priority too :D
      Keep Visiting !! Keep in touch :)

  28. Thank you for your help!

  29. Hi How are you?

  30. thanks for your post , You saved a lot of time

  31. [...] http://nehasinha.wordpress.com/2008/05/23/programmticallyc-adding-deleting-copying-and-downloading-a… [...]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 26 other followers

%d bloggers like this: