Home > Delete and download files to, Object Model, Sharepoint List, SharePoint Object Model, Sharepoint Upload, Upload multiple Files to Sharepoint Files > How to attach/delete/upload files to SharePoint List Item using Object Model

How to attach/delete/upload files to SharePoint List Item using Object Model

August 8, 2009

Welcome Reader,

I have moved to a new blog site, so you can get same content from below new site URL!!

http://dishasharepointworld.blogspot.com/2009/08/how-to-attachdeleteupload-files-to_08.html

Please feel free to post your comments/feedback into new blog, I’ll be more than happy to assistant you.

Sorry for any inconvenience!!

Disha Shah

  1. Arindam C
    October 7, 2009 at 6:32 am | #1

    Hi Disha

    This post is good. I’m also working in Sharepoint , I have a requiremnet, we have a webpart for slide show, this webpart takes images from an image list and shows them, now to use this webpart you need to 1> Upload all the images in the image list 2> Select the image list name from the Modify shared webpart dialouge ( we have customized it),we need to develop a sharepoint picker, from which users can upload docs to the list .

    Can you help in this regard.

    Thanks
    Arindam

    • dishashah08
      October 8, 2009 at 6:08 am | #2

      Hey Arindam,

      Thank you very much for your comment.

      Please let me summarize here to see whether I am following you correctly or not for your requirements, you are saying that you need to develop functionality (SharePoint picker type of thing) from which user can upload documents to your list, and this has to be in your web part only, please correct me if I am wrong here…

      If that’s your case then you can put ASP: File Upload control into your web part and write code on clicking of save button, which will take posted file name and upload same file into document library with the help of SPFile and other classes from SharePoint object model.

      If you are looking for something else then please let me know.

      Thanks,
      Disha Shah

  2. Carla
    October 26, 2009 at 4:42 pm | #3

    Hi Disha,

    I am very new to Sharepoint and ASP. I’m stuck and am looking all over the net for some help. I am using a Survey web part (I’m assuming it is a webpart that came with Sharepoint vs a web part someone in my organization created). I need functionality that allows the responder to upload an attachment to their survey response. Do you think your code will work in my case by adding it to the form “HEAD”? Or do you think I will need to use the ASP File Upload option?

    If so, I’m certain I will be able to Google it and find something, but if you have first hand experience, I would love to know your approach with specific code samples.

    Thanks in advance.

    • dishashah08
      October 27, 2009 at 1:34 pm | #4

      Carla,

      Thanks for the comments.

      Survey list is a special type of list, which has limited type of features into it, like we cant add custom columns or manages content type, attach files etc.

      So I prefer to develop Custom field Type. I have developed custom field type which asks from user for country and from country it displays related state names. You can also do same thing, you can create a custom field type which asks from user to upload a document and it uploads that file to document library and stores that path as your field value and then add a new question to survey list which has type of your custom list and you can name it like “Attachment”.

      This is the one way. Second way would be to create a new custom list which is not type of survey but try to make custom list same like Survey list. This is easiest way :)

      Hope it will help to you.Thanks,

      Disha Shah

  3. Nesreen
    November 2, 2009 at 7:24 am | #5

    Dear Disha,
    Thank you for this great post.
    I want to ask you abour the variable “txtFileName”, what is it and how can I get it?

    • dishashah08
      November 2, 2009 at 1:58 pm | #6

      Hello Nesreen
      “txtFileName” is the Textbox that I have taken for providing the functionality to user, they can provide their own filename into “txtFileName” textbox.

      It means whatever file you have selected by File Upload Control it replaces that filename with name entered into txtFilename textbox.

      Example:
      You have selected “test.txt” from File upload control , but you want to upload that file with different name say “Real.txt” , so you need to specify “Real” in that txtFilename text box

      Hope this helps!!!

      Thanks and Regards
      Disha Shah

  4. Steven Adams
    November 5, 2009 at 2:46 pm | #7

    Thank you very for the interesting post.

    I have a similar funcationality, but how does your interface look like for add/deleting/uploading mutiple documents?
    Can i search for the documents uploaded in a list item? meaning show me all the listitem which has only this type of download?

    Please share your inputs

    Thanks

    • dishashah08
      November 6, 2009 at 10:28 am | #8

      Steven

      Thank you for the comments.

      Answer 1:-
      Here is webpart interface how it almost looks like this,

      File Name Delete
      Attachment1 Delete
      Attachment2 Delete
      Attachment3 Delete

      When you click on delete, it will invisible that row, and when you click on “File Name” Hyperlink, it will ask you to open or view File.
      Answer 2:-
      We can’t search from list item attachments or the documents which are uploaded to custom list.

      As a alternative, may be you can try this thing – create separate document library into SharePoint site and give facility to user for uploading documents to document library instead of attaching documents to custom list, then create one column into document library which is lookup to custom list, in this way, we can have and create relationship between document library and custom list, so at the end, user can upload documents/attachments to document library and its associated with custom list. Then user can search based on attached documents from document library.

      Thanks,
      Disha Shah

  5. Naren
    November 5, 2009 at 3:59 pm | #9

    I tried your code but when i upload the documents to SP lit, i got access to filepath is denied. i don’t find any file in env variable %TEMP% location. Can you point what is going wrong with me. Thanks!

    • dishashah08
      November 6, 2009 at 2:59 pm | #10

      Naren,

      There are many possibilities why you get error “access to file path is denied”
      May be you can try some of the below things.
      1>Check the File Size. If it is more than 50MB Please refer this link to allow users to upload more than 50MB file to SharePoint site.

      http://dishashah.wordpress.com/2009/11/04/how-to-upload-big-size-of-
      documents-to-sharepoint-site/

      2> you do not have permission for file path, may be it refers to “Double Hop” Problem.
      Double Hop -
      The double-hop issue in SharePoint occurs when IIS attempts to pass the user’s NTLM credentials to a service that is running on a server that is either not part of the requesting server’s farm, or not running directly on the web server.

      It’s my wild guess only!

      Thanks,
      Disha Shah

  6. skamuju
    November 9, 2009 at 8:32 am | #11

    How Can I Upload documents into sharepoint document library with out user interaction. i mean automatically the files should get uploaded into the doc lib from a local hard disk of the server.
    As the situation is critical, Any relevent posts is encouraged.
    Thanks In Advance
    Skamuju

    • dishashah08
      November 10, 2009 at 3:08 am | #12

      Skamuju

      Yeah, you can do that by creating SharePoint timer job; here are some of the steps to upload the documents from local hard drive to SharePoint document library without user interaction.

      1. Write code which will upload docs into doc lib
      2. Put your code into SharePoint timer job
      3. Configure timer job which will run on specified time
      4. Deploy timer job

      Hope this will help you!

      Disha shah

  7. November 12, 2009 at 12:59 pm | #13

    Hi Disha,

    I think this post is really very good.

    I also work in SharePoint Server and also work in Project Server, Windows Workflow Foundation and runs a SharePointKings blog entierly on SharePoint and WWF.

    I want to know if it is possible to create a custom File Upload field in sharepoint. Can you give me some highlight on this?

    the requirement is, User should be able to upload multiple files at one go in NewForm.aspx and these files should go as a multiple attachments for a single list item.

    Your thoughts appriciated.

    • dishashah08
      November 13, 2009 at 2:00 am | #14

      Malay,

      Thank you for your comment. It’s good to know about your skill set.
      You can achieve your requirement in this way – you can use out of the box SharePoint Web Controls – Attachment button, Attachment Upload and Attachment field control, you need to write code which will upload all selected files from user to current or particular SharePoint list item, you can put your code into custom ASPX page or custom web part.

      Here is very good link which will explain you how to do above things – step by step.

      http://www.pointsharepoint.com/2008/12/list-attachments-in-webpart-solution.html

      Or you can create your own Custom Field type which allows you to upload multiple attachments

      http://dishashah.wordpress.com/2009/11/05/step-by-step-tutorial-for-how-to-create-and-implement-custom-field-type-in-sharepoint/

      Thanks,
      Disha

  8. sreeni
    November 16, 2009 at 7:07 pm | #15

    Hi,

    I tried to use the download attachment code in a custom webpart, but its throwing so many errors. Please direct me. I am using the above code for an anonmyous user……

    • dishashah08
      November 17, 2009 at 1:46 am | #16

      Hi Sreeni

      Can you please let me know which kind of errors it is throwing; if it is related to “Access Denied” then you should run your code in SPSecurity.RunWithElevatedPrivileges(delegate() .

      If it is thowing other than that, provide me description of the error so I can redirect what you need to do.

      If you just get one line error message and to get detailed error message please refer this link.
      http://dishashah.wordpress.com/2009/08/08/how-to-display-detailed-error-messages-into-sharepoint-page/

      Thanks
      Disha Shah.

  9. dee
    November 17, 2009 at 2:48 pm | #17

    Awesome post..I am going to copy and paste it! Thank u so much

  10. sreeni
    November 17, 2009 at 2:59 pm | #18

    Hi Disha, Thanks for your reply.
    I resolved those errors. Do you have idea of downloading a listitem attachment in anonmyous mode?

    Thanks
    Sreeni

    • dishashah08
      November 18, 2009 at 1:37 pm | #19

      Hi Sreeni

      Yeap, you need to write your download attachment from listItem code under SPSecurity.RunWithElevatedPrivileges(delegate() block.

      This is the link you can refer for that.
      http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx

      Hope this helps!!!

      Thanks
      Disha Shah

  11. November 18, 2009 at 5:32 pm | #20

    You can also impersonate the user so that for the particular code you want to run you can give the permissions..

    Here is the code with explanation
    http://sharepointforums.blogspot.com/2008/10/impersonating-user.html

  12. sreeni
    November 20, 2009 at 2:09 pm | #21

    Hi,
    Thanks. I resolved that issue but another issues came up.
    I am using HTTP context to show File downlaod dialog box, after downloading button events are not working… is there any way to resolve this …
    I am trying to refresh the page but still not working…

    thanks
    Sreeni

    • dishashah08
      November 21, 2009 at 1:50 am | #22

      Srini,

      I think the problem you are facing is known issue if you are working with something related to Response or sometime HTTP context Object.

      I have alternative for this – create one separate ASPX page(child page)/web part in which write your server code which will download file on page load, and call this page from main page, I mean create one child page which will have logic for downloading file, and open child page from parent page, so in this way when user clicks on “download attachment icon”, it will open one popup window and it will open respective file and then you have all control on parent page, so all button events will work in parent page.

      Thanks!
      Disha

  13. Parisa N
    December 1, 2009 at 10:39 am | #23

    Hi Disha Shah

    Thank you for your useful posts, I really need your guide. I want to know can we save uploaded file in libraries or even attached files in lists of sharepoint, in a file server? I mean not in the SQL. If yes, would you plz tell me how?!

    Thank you in advanced
    Parisa

    • dishashah08
      December 1, 2009 at 7:59 pm | #24

      Parisa,

      Yeah, you can use WebClient Service to upload the file from SharePoint Document Library to File Server. Access all SPFiles from listitem.attachments and take its url and pass to following function.

      Sample Code:
      SaveFile(attachmentfilepath, FileserverURL);
      public bool SaveFile (string attachmentfilepath, string FileserverURL)
      {
      try
      {
      using (WebClient webclient = new WebClient())
      {
      webclient.UseDefaultCredentials = true;
      webclient.UploadFile(attachmentfilepath, “PUT”, FileserverURL);
      }
      }
      catch(Exception ex)
      {
      return false;
      }
      return true;
      }

      Thanks,
      Disha

  14. Pradeep Kumar
    January 6, 2010 at 3:31 pm | #25

    Dear Disha,
    I’m very new to sharePoint.
    Your blog helped me in create a custom webpart for uploading files in SharePoint ListItem/doc library.

    Your blogs are step by step and helped much to new learners in sharepoint.

    Thanks & Regards
    Pradeep

    • dishashah08
      January 6, 2010 at 4:29 pm | #26

      Hi Pradeep,

      Thanks for comment.
      If you have any questions, doubts for sharepoint development or configurations leave a comment and I will get back to you with suggestion.

      Thanks
      Disha Shah

  15. Junaid Arif
    January 17, 2010 at 4:51 am | #27

    I have a requirement that I need to write a custom web part that will display shared documents in window explorer style. So on the let side all the folders displayed in a tree view and on the right all the files for the selected folder displayed. Also we must have sharepoint default functionality like uploading, deleting and modifying, checking in and checking out files. Do you know if we can do this and how?

    • dishashah08
      January 18, 2010 at 7:38 pm | #28

      Hi Junaid Arif

      You can achieve your requirement by developing a customized webpart and with the use of “Object Model”.

      You can take treeview and iframe for displaying like on left had side put treeview and in treeview show folders-subfolders in explorer manner (one design functionality in treeview) and right hand side when they select a particular file write event on treenode selectednode changed , display that file on iframe which is on right hand side.

      You can put all your other functionality as buttons named as “upload”, “download” and use object model power to develop each functionality on selectednodechanged of treenode.

      Hope this helps
      Disha Shah

  16. Junaid Arif
    January 18, 2010 at 11:00 pm | #29

    Thank you so much for replying this really helps. Have another question, is there a way we can add the sharepoint standard menus like New, Upload, Actions and Settings in the customized web part?

  17. Safi
    January 25, 2010 at 4:42 am | #30

    Dear Disha Shah,

    Thanks a lot for you valuable post.I have a requirment To upload ,Delete ,download files from/to document library.I followed you with the same Code.For me Upload and Delete is working fine.But download is not working properly.When i click download button ,a pop up window is opening,its asking Save,Open or Cancel.But if i click open or save its not opening the exact file which i attached.Its showing the source code for UI.When i debug the code the exception is “this is not valid virtual path”.But i check the path is correct.Please help me to come out from this issue.

    (i Put ur exact code for download except the path section)

    • dishashah08
      January 26, 2010 at 1:59 am | #31

      Safi

      Can you please write me back with change you made in your code for path section? That helps me out to solve your problem.

      Thanks
      Disha Shah

  18. amit
    January 28, 2010 at 11:28 pm | #32

    HI Disha,

    Would like to add multiple attachments to list item by customising the newform.aspx insteading of creaing a webpart? Is it possible?

    Regards
    Amit

    • dishashah08
      January 29, 2010 at 1:52 pm | #33

      Amit

      Very good question.Yes you can add multiple files via newitem but there are some disdavnatages are there too.

      For Example, If you have “title” field as compulsory , now you started to add new items and insert multiple files in that list and you did not enter value in “title” field and now when you press save all attached files gone.

      But one advantage is no need to write code and deploy webpart.

      Hope this helps.

      Thanks
      Disha Shah

  19. Ravi
    March 10, 2010 at 3:37 pm | #34

    Is there a way to attach file in Sharepoint survey?

    • dishashah08
      March 10, 2010 at 8:37 pm | #35

      Ravi

      Yes, as you know there are so many Field types are available like “Multiple Line of Text”, “Person or Group”.

      The same way you need to create one Custom Field type which is type of “File” and you can select that type when you add a new survey question.

      Hope this Helps
      Best Regards
      Disha Shah

  20. Sohil
    April 8, 2010 at 10:30 am | #36

    Hi Disha

    A newbie to Sharepoint

    Nice post really helped to upload multiple docs .

    My question is based on project Task

    The Idea is around standard wss feature “Project Tasks Under Tracking.But its very limited as for each project and project tasks I have to crate folders. So I was thinking is it possible to do the following

    One Page that has a custom list with:

    1. Project name

    2. Project manager

    3. Project stage (initiate, proposal, in-progress, closed)

    4. Initiate date

    5. Proposal date

    6. Work start date

    7. Progress status (On-time, Delay Customer, Delay Us)

    8. Project Documents (when clicked on can attach multiple docs to this project) “Your post help me a lot in creating thing”

    9. Project plan (when clicked on – it brings up project tasks as exists project tasks under tracking)

    10. Issues ( when clicked on brings up issue tracking as under tracking – and can document multiple issues )

    11. Change Order ( when clicked on bring up a text open area to write and then can attach a document)

    12. My tasks (when clicked on displays tasks assigned to uses who signs on)

    Obviously number 1-7 is very easy. Number 8 This post helped me in creating it.But I do not know how to do number 9-12.

    Can you please help me in this

    Thanks

    Sohil Patel

    • dishashah08
      April 12, 2010 at 2:05 pm | #37

      Sohil

      I think whatever you had done for step 8 means custom coding the same way you need to go with for steps 9-12.
      You just need to design how the client need and put custom code into it…

      In that custom webpart you can create a table add add 12 rows as ur steps and just add controls and add logic according to that.

      Some Suggestions Like

      Fot Step 9:
      You can put one grid for displaying Project Plan.

      For Step 10
      Grid which displays existing Issues and one textbox and Submit Button where user can submit their on issues one by one and when they add a new issue it should automatically add to Grid.

      For Step 11:
      Text Box and File Input button with Submit button and grid where they can see whetever they uploaded and may be they can delete.

      For Step 12:
      grid where it shows all tasks related to that user.

      Hope this helps
      Disha Shah

  21. Aravind
    April 13, 2010 at 8:30 pm | #38

    Hi Disha,

    WE are creating a survey .The requirement is that whenever the user finishes the survey it should send an email notification to the author.I have tried attaching workflow to the survey,but it is throwing error!! Any idea how to implement this requirement will be of great help!!

    • dishashah08
      April 14, 2010 at 2:14 am | #39

      Arvind

      Well you can do two things!!!

      You can send me workflow error and I can look into that error. For the descriptive error please check sharepoint log and give me the error description related to workflow.

      You can use eventhandler and write sendemail code in survey itemaddded or itemupdated.

      Hope this helps!!!!!
      Thanks and Reagrds
      Disha Shah

      • Aravind
        April 14, 2010 at 6:16 pm | #40

        Ok..Thanks a lot..But can’w we do OOTB.I tried attaching on simple OOTB approvla workflow and it throws error!!I think we cannot attach workflow’s to a survey list..What is your though on this?So customization is the last resort?

      • dishashah08
        April 16, 2010 at 2:33 pm | #41

        Hi Arvind

        We can attach OOTB workflow to Survey List ..Can you please let me what is the error?

        Thanks & Regards
        Disha Shah

  22. May 20, 2010 at 1:45 pm | #42

    Hi Disha

    Can you tell me if there is a relatively straightforward way to export an individual record from a list for printing – ideally in a format that can be edited to provide a corporate look and feel. I’m creating a list of project details and want to be able to generate printed case studies that incorporate output from specific fields within an individual Project Record.

    Many thanks in advance

    Jeremy

  23. nagaraj
    August 4, 2010 at 8:02 am | #43

    Hi Disha

    Thanks for the post just i am crawling the net i have dought i want the doucument to upload by only certain groups not all others.in sharepoint using object model if have any source plz share

    • dishashah08
      August 5, 2010 at 1:35 pm | #44

      Hi Nagaraj

      First create a group and add a person who has the access to upload documents to that document library. Let us say name is “Upload Group”

      Well you can write the code as below when you add a document to your SharePoint Document Library through Object Model.

      SPGroup group = SPContext.Current.Web.SiteGroups["Upload Group"];
      if(group .ContainsCurrentUser)
      {
      \\Code for add a document
      }
      else
      {
      //Write a message for “Access Denied”
      }

      Hope this helps
      Thanks & Regards
      Disha Shah

      • nagaraj
        August 10, 2010 at 11:45 am | #45

        Hi Disha

        Thanxs for for useful hint!
        can u please tell me something about infopath if u know ! using custom code using VSTA

  24. nagaraj
    September 3, 2010 at 11:38 am | #46

    HI Disha
    I am newbie of using javascript in custom webpart development i need whenever the other group doesn’t have permission of uploading the doc some javascript alert need to excute rather than error page!

    • dishashah08
      September 13, 2010 at 12:50 am | #47

      Hi

      I have a question for you. Are you developing a new custom webpart? If yes , then you can do that by writing javascript code on controls’s onclick event.

      If not, please give me a detailed description of your requirement on my new blog URL.

      FYI: I have moved to a new URL that is http://dishasharepointworld.blogspot.com and I have moved all contents to new URL.

      You are referring the same blog on this URL is
      http://dishasharepointworld.blogspot.com/2009/08/how-to-attachdeleteupload-files-to_08.html

      I REQUEST please post comments now on wards to their blog.

      Thanks and See you on new blog URL
      Disha Shah

  1. No trackbacks yet.
Comments are closed.
Follow

Get every new post delivered to your Inbox.