How to: Uploading a File to a SharePoint Library Site from a Local Folder
I am currently developing an application that will help my team (Office Developer Documents) to manage all the metadata associated with the publishing process in MSDN. The name of the tool is Rawhide and it’s a Web-based application. I am really excited of developing this tool because I am working with Whidbey, ASP.NET 2.0, SQL Server, Windows Sharepoint Services, and a cool set Office development features. Soon I will start adding Office “12” enhancements such as Excel Services and Windows Sharepoint Services “v3”. I can’t wait!
I am learning a lot from my peers about how interesting it is to publish content in MSDN and I hope this tool will improve our working experience and become a great source of code snippets that I can share with the community.
Today I was reading the newsgroups and I was looking at lots of posts where developers are looking for code that will help to upload programmatically files to a SharePoint library. I was surprised to see that there are lots of developers struggling with this issue. I am too :). One of Rawhide’s features is to submit our articles, code samples, and art to a SharePoint Library.
I found two great articles that are helping me out to accomplish my mission. I know there are many ways of doing that, but this is the recommended one by Microsoft and I love it because it has just what I needed and it has code in C# and VB.NET:
Uploading a File to a SharePoint Site from a Local Folder
I also found this page that has all the information I need to work with the SPFileClass.
And finally, I found this interesting blog entry at Bill Simser’s blog where he talks about the Syncronization of Office Document Properties with WSS Document Libraries. I haven't tested this yet, but apparently, if you create the following properties in a Sharepoint library or list:
Subject
Author
Manager
Company
Category
Keywords
Comments
Hyperlink base
"The MS/Office documents that are upload inherit such corresponding custom MS/Office properties : "
Subject0
Author0
Manager0
Company0
Category0
Keywords0
Comments0
As soon as I complete my "upload files to SharePoint" features in Rawhide, I will keep you posted with the outcome.
Comments
Anonymous
November 03, 2005
I too noticed a lot of requests for uploading files. I posted a code snippet on my weblog (http://www.schaeflein.net/blog/2005/07/12/ProgrammaticallyUploadAFileToADocumentLibrary.aspx).Anonymous
November 03, 2005
I saw that! Thanks for sharing and writing about that, I was quite surprised too.Anonymous
November 17, 2005
When we try to use the code as mentioned in the msdn I am being asked for credentials. What permissions do I need.
This works only if I am an administrator on the machine.Anonymous
January 18, 2006
I think there is confusion on what you need to reference. Do I have to develop and run a windows app written in c# on a server that has Sharepoint installed to use the local dlls? I can easily use http://rmcazpts01/_vti_bin/Dws.asmx as a web reference to create folders in SharePoint but there is no outright "Upload File" web services. The only thing that sounds close is UpdateDwsData and this is the only option in dws.asmx that does not have a code example. Please explain if you can. The guys blog underneath yours also doesn't explain what you need to reference either. I don't want a web application.Anonymous
January 18, 2006
Hi everyone,
Thanks for your comments and questions. I talked to the product team and another option to upload documents to a SharePoint v2 library is building a custom web service. Here is how:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odc_sp2003_ta/html/odc_writingcustomwebservicesforsppt.asp
This scenario works well when you are trying to upload a document to a document library that lives in a different web server from your web-based application.
About security, make sure that the user that gets impersonated (if you are using Windows Authentication) has write permissions at the SharePoint library. This is a matter of authorization.Anonymous
April 24, 2006
Wait a minute guys. I'm a regular old everyday user. Do you mean to tell me that my "UPLOAD FILE" button in Sharepoint won't allow me to upload a few MS Word and Acrobat files from a CD in my "E" drive unless I use the computer code that you are using?
When I attempt to upload my files from the CD Sharepoint wants me to browse the CD folders and select one file at a time. This is totally impossible. I have some 60 files.
Help!!!!Anonymous
April 30, 2006
Wait a minute guys. I'm a regular old everyday scripter.
I don't own the SharePoint server; I don't want to use a web browser.
I want to write code once to upload one or more files and have it run whenever it should run. If there is a web service to get a list of versions of a file, why isn't there a web service to upload a new version?Anonymous
May 01, 2006
Errol-
After much searching, I found the scripting information that I needed. You could use it for exactly what you need if you are capable of a little VBScript-ing. (msxml2 and adodb are Microsoft libraries that most systems would have installed with various products.)
http://sqljunkies.com/WebLog/tpagel/archive/2005/12/23/17682.aspx
I hope this helps you. Sorry, I don't have time right now to write you an example.
Tom.Anonymous
May 04, 2006
I downloaded the code sample from the following location:
tp://msdn.microsoft.com/library/default.asp?url=/library/en-us/odc_sp2003_ta/html/odc_writingcustomwebservicesforsppt.asp
I can tell you I have an ASP.NET 2.0 application in production that is using the web service and it's quite smooth and easy to configure.
You just need to:
1. Run the .bat inside the download.
2. Add a reference to the web service from your project.
3. Turn on impersonation
4. Add permissions to the users that will be uploading documents to the SharePoint Document Library.
5. Be happy and smile because it works!Anonymous
May 04, 2006
After doing some research and some tests, I found a very easy way to do that and now I want to share with you the approach I followed since you might find it useful as well.Anonymous
May 11, 2006
Not to pick on you, Erika, but Microsoft just doesn't get it. Quit making addons that constitute patches; start making service packs.
SharePoint users should not need to ask SharePoint administrators to install addons; At worst, they should only have to ask them to upgrade to a current, Microsoft-supported version that is a complete product. By complete, I mean that anything that can be done by a user through a web browser should be able to be done by a user application that consumes a web service that is part of the product.
Anyway, keep up the enthusiatic sharing of addon information--some SharePoint developer/adminstrators will find it very useful.Anonymous
July 05, 2006
i want to upload a file from my local folder to a sharepoint server which is on some other machine......will the above program works for it?.....Thanx for any help......Anonymous
July 28, 2006
I need the exact C#.Net coding for uploading a file from local folder to sharepoint document libraryAnonymous
December 18, 2006
Hi, Office 2003, WSS2.0 We're currently customizing WORD for a group of policy analysts. Their current way of operating is to use Word to open files stored on a file server. We are looking at using SP as the document store because of its checkin, check-out and versioning. I think, based on the article(http://msdn2.microsoft.com/en-us/library/ms916810.aspx), that we can integrate the checkin, checkout. What about versioning? Any examples out there? I've looked, very briefly at http://<servername>/_vti_bin/versions.asmx. I was expecting something called "add version" or something like that. Is there a way to handle versioning of documents in a similar way? Thanks for any assistance, PaulAnonymous
December 27, 2006
How about uploading a new workbook to sharepoint via an excel macro? any helpon that???Anonymous
January 07, 2007
Hey guys, can anyone tell me how to deploy spFiles.asmx on MWSS 3.0. I am getting SharePoint Security Exception in my smart client application which is trying to upload the files. ThanksAnonymous
January 29, 2007
The comment has been removedAnonymous
March 28, 2007
I recently did this at work and tried the methods you have all talked about. Without letting the cat out of the bag entirely (proprietary, etc), you should consider using the "Copy" web service, traditionally found at: http://sharepoint_server/_vti_bin/Copy.asmx Once you have this service, you can load the desired question into a byte stream: //provided by the copy web service, FieldInformation[] fieldInfo = { new spps07.FieldInformation() }; byte[] file = System.IO.Loadfile( LocalFileName.ext ); Finally, set the extra params for Copy.CopyIntoItems() string[] srcUrl = "http://abc.com/" //put any url here string[] destUrl = {"http://sharepoint_server/folder/RemoteFileName.ext"}; // This service can upload to multiple urls at once! And that's it. Plug in the desired info, etc, and it will upload (much easier than using spsite, etc...)Anonymous
March 28, 2007
The comment has been removedAnonymous
April 02, 2007
I am coding a macro which currently send a file to respective persons through mail. I wouold want to introduce a funcionality in this macro where the files get uploaded on a common sharepoint folder. The samples you mentioned are through asp.net & vb.net. Isnt it possible through VBA (i.e excel macros) ?Anonymous
May 10, 2007
I too have run into this pain, admittedly in wss 2.0, although I haven't seen anything in wss 3.0 apart from LCValentine's Copy suggestion (thank you). I needed to upload a file to a document library from a remote location AND set the columns/fields on the document at the same time. Ended up having to write a custom web service to do it (although updating the fields caused a 2nd version to be created - doh). Before I go down that route - anyone aware of any way of doing it just using the supplied services? Erika? You'd think uploading a file was pretty fundamental stuff really .... LJAnonymous
May 12, 2007
The comment has been removedAnonymous
May 21, 2007
I'm using a web service to upload files to a document library and it works great...except when a file of the same name already exists. How in the world do I get my files to overwrite? Here's a little snippet of what I'm doing: SPSite site = SPContext.Current.Site; SPWeb web = site.OpenWeb(); SPFolder folder = web.GetFolder(pathFolder); string fileURL = fileName; SPFile file = folder.Files.Add(fileURL, fileContents, true); return file.TimeCreated.ToLongDateString() + "::" + file.Title;Anonymous
May 25, 2007
I wanted to find out how I could upload a document and supply some properties in one operation. I just used reflector to poke at the Copy web service and saw that it just uses SPListItem.Copy under the covers and that you can supply it a hashtable of property information that magically gets mapped to the columns in your content type. I just wrote a custom web service method to handle this task using that technique. This code works for me, so tweak it for your specific content types. This leaves the document still checked out, so if you need it checked in, you'd have to add that step. [WebMethod] public void UploadDocumentWithProps(string destinationurl, byte[] contents, string prop1, string prop2) { string sourceurl = "http://tempuri.org"; Hashtable props = new Hashtable(); SPCopyFieldInformation cfi = new SPCopyFieldInformation(); cfi.InternalName = "Prop1"; cfi.DisplayName = "Prop1"; cfi.Type = SPFieldType.Choice; cfi.Value = prop1; SPCopyFieldInformation cfi2 = new SPCopyFieldInformation(); cfi2.InternalName = "Prop2"; cfi2.DisplayName = "Prop2"; cfi2.Type = SPFieldType.Choice; cfi2.Value = prop2; props.Add(cfi.InternalName, cfi); props.Add(cfi2.InternalName, cfi2); SPListItem.Copy(sourceurl, destinationurl, props, contents); }Anonymous
May 25, 2007
The comment has been removedAnonymous
July 11, 2007
The Copy service works fine, even for meta data , Thanks a lot. The method using SP object is not webservice based since we require The Microsoft.SharePoint.dll as reference in it.Anonymous
July 19, 2007
Does anyone know if there is a way to create a Sharepoint (2.0) folder (with a date parm as part of the folder name) and also copy excel files into the new folder through VBasic code. I want to automate a process via an MS Access application to perform such a function. Thanks.Anonymous
September 13, 2007
I'm almost in tears with frustration at trying to get round this upload issue. We are using the upload the code as mentioned in the msdn article and it works OK in development and test environments for users with administrative rights. However, users in our live system are being asked to supply credentials even though they are uploading to their own doc library. Can anyone explain what's going on here, please!!! If we need to supply admin account credentials, how would this be coded? Hope someone can help. Thanx.Anonymous
October 25, 2007
This might help... http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2323967Anonymous
November 01, 2007
hi, about the upload issue, I have the opposite problem. I want to copy all files in a document library in sharepoint to my local drive. Is this possible and can somebody tell me how? my code is quite similar to yours, I don't get any error but it doesnt do anything. please help me... please... I will really appreciate it :DAnonymous
November 05, 2007
Having said all that, what is the MOSS 2007 way to upload files created in an ASP.NET 2.0 web application hosted on a different server into a Sharepoint document library?Anonymous
November 20, 2007
You all forgot to answer my only & ultimate question:- Creating an ASP.NET 2.0 website where any user can browse for a document from their own drive and then upload it to a document library?!!?!?! Can someone give a "FULL" example that really works PLEASE :( ?! i'm new developer and not fully aware of web services programming S.O.S ?Anonymous
November 22, 2007
We are in the same situation as everyone else appears to be in in this thread: we want to load a file into a MOSS document library and create a new version if the file already exists. Having spent many hours looking for solutions, I have not been able to find any information to do it beyond the standard files.add method! There are heaps of articles by so called 'authorities' who have done nothing less than scrape MS web pages as their own, but none appear to have actually done it! Instead of all the waffle, can someone who really knows what they are talking about please answer the question with a worked example: how does one actually upload a file to an SP doc library and have it create a new version ? The amount of time we have spent mucking about with Sharepoint, doing Microsoft's documentation and testing for them, I could have developed our complete solution in C# myself! C'mon MS, if you're serious about this product, you've GOT to document it PROPERLY. As it stands, it is far too difficult to customise MOSS and until it becomes significantly easier, MOSS will not take off. Most of my clients look at it, comment that it is too difficult and then discard it. Perhaps people need to recognise that it isn't a general purpose web site development tool and that custom coding (make instead of buy) can often be more productive than trying to show-horn the business into a third-party product!Anonymous
December 06, 2007
Hi All, Can anyone help me out with a VBA code snippet to load a excel file to a sharepoint. The excel source is on my local machine. I want to load it to the shared point. Thanks for any helpAnonymous
December 30, 2007
All these posts and yet no one was able to supply a working example with source code of how we can upload a file in MOSS 2007 library via an ASP.NET 2.0 web application. I'm losing sleep over this issue please help.Anonymous
January 07, 2008
Shocked Sam - some variation of the code below should work...hope this helps..! SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite("http://team.rkaushik.internal")) { site.AllowUnsafeUpdates = true; using (SPWeb web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; SPWebApplication webApp = site.WebApplication; webApp.FormDigestSettings.Enabled = false; Stream fStream = File.OpenRead("c:\temp\test.txt"); byte[] contents = new byte[fStream.Length]; fStream.Read(contents, 0, (int)fStream.Length); SPFolder folder = web.GetFolder("Test"); SPFileCollection files = folder.Files; SPFile added_file = files.Add("http://team.rkaushik.internal/Test/Test.txt", fStream, true); fStream.Close(); fStream.Dispose(); web.Update(); webApp.FormDigestSettings.Enabled = true; web.AllowUnsafeUpdates = false; } } });Anonymous
February 14, 2008
Here's how I did it in VB.net 2008 with wss3/moss (thanks to LCValentine@gmail.com) Add a service reference to the copy.asmx in the _vti_bin folder of your wss 3 server, I called it SPS Dim fileInfo As New System.IO.FileInfo("filename string") Dim fileStream As System.IO.FileStream = fileInfo.OpenRead() Dim myFile(fileStream.Length) As Byte fileStream.Read(myFile, 0, fileStream.Length) fileStream.Close() Dim copy As New SPS.CopySoapClient Dim result() As SPS.CopyResult = Nothing Dim fieldInfo() As SPS.FieldInformation = {New SPS.FieldInformation()} copy.CopyIntoItems(" ", New String() {"http://url to document library/filename"}, fieldInfo, myFile, result) If result(0).ErrorCode <> SPS.CopyErrorCode.Success Then MsgBox("Could not save to document library: " & result(0).ErrorCode & " " & result(0).ErrorMessage) Else MsgBox("Successfully published to document library") End If I hope this helps someone elseAnonymous
February 14, 2008
BTW, I also had the set it to use ntlm authentication in the appconfig for it to pass the current user's details to sharepoint For the binding on the SPS service reference change the generated security node to the below <security mode="TransportCredentialOnly"> <transport clientCredentialType="Ntlm" proxyCredentialType="Ntlm" realm="" /> </security>Anonymous
February 21, 2008
The comment has been removedAnonymous
February 28, 2008
Hi Erika, I am trying to save the active document with its bookmark text replaced into share point document library using SaveAs() method. I am specifying the document location as UNC. when I try to save the document from client machine on my local network, the save process hangs for sometime and then the document is saved. I feel that the saving process is taking too much time than the actual time. Is there any way of overcoming this issue. Thanks in advance, yenkayAnonymous
March 04, 2008
The comment has been removedAnonymous
March 05, 2008
Sean, glad it worked for you, and yes, it's using the SharePoint API so it has to run on the actual SharePoint 2007 server - no way around that.Anonymous
March 06, 2008
i have a requirement that, i need to store the test.xml file to sharepoint document library. and once again i open the test.xml file and made some changes, and then i want to save it in same file name with different version. all these things i need to do by c#. is it possible? can any one please help for this? its urgent!Anonymous
June 02, 2008
i have a requirement that, I have created acustom webpart where i am trying to upload a file to the document library. From the system account when i am trying to upload a document it's working fine. But if i logged in from other accout it's not allowing and throwing the bellow exception " Access to the path 'C:Documents and SettingsSPSAdmin.WIN2003DesktopUpload Document.txt' is denied." This is my code SPWeb site = SPContext.Current.Web; SPFolder myFolder=site.GetFolder("ProjectTracking"); fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName); if (fileName != null) { site.AllowUnsafeUpdates = true; SPFileCollection myFiles = myFolder.Files; string strFilepath = System.IO.Path.GetFullPath(inputFile.PostedFile.FileName); StreamReader sr = new StreamReader(strFilepath); Stream fStream = sr.BaseStream; contents = new byte[fStream.Length];//HERE I AM GETTING ERROR fStream.Read(contents, 0, (int)fStream.Length); fStream.Close(); SPFile myFile = myFiles.Add(fileName, contents); site.AllowUnsafeUpdates = false; lblMessage.Text = "Sucessfully Submited"; } all these things i need to do by c#. can any one please help for this? its urgent!Anonymous
June 20, 2008
Hi - the sharepoint web services are a nightmare. There's a much easier way to do this: public static void UploadFileToFolder(byte[] FileToUpload, string PathAndFileName, System.Net.NetworkCredential nc) { WebClient w = new WebClient(); w.Credentials = nc; w.UploadData(PathAndFileName, "PUT", FileToUpload); }Anonymous
June 20, 2008
Hi Michael, I have a question for you, I saw that you are adding a reference to Microsoft.SharePoint. I do not have SharePoint installed on my machine. I am just adding web services to the application and using it. But looks like if I go by your method, I need to have SharePoint installed. Can I not do just by using Web Services? This is how I am using web services: Added Web Reference to: <servername>Lists.asmx and others... then initialised WS classes: SP_DocumentWorkspace.Dws ws_DocumentWS = new Dws(); ws_DocumentWS.Credentials = new NetworkCredential("username", "password", "domain"); Please help me with the code for retrieving all the documents from SP Site and then uploading documents to SP Site. Thanks, Pooja.Anonymous
August 12, 2008
Can any one tell how to use CopyIntoItems from the copy.asmx webService. it gets copied on the same server but unable to copy on other server.Anonymous
September 23, 2008
In case it is of any use to anyone, I coded up a lot more since the last snippet of example code, and here is the project site where the full code is available.Anonymous
October 21, 2008
Anisha said: I am coding a macro which currently send a file to respective persons through mail. I wouold want to introduce a funcionality in this macro where the files get uploaded on a common sharepoint folder. The samples you mentioned are through asp.net & vb.net. Isnt it possible through VBA (i.e excel macros) ? Any sample code for this ?Anonymous
November 05, 2008
Hi, When i upload a document to document library in sharepoint, the 'DateModified' column shows the uploaded date/time value. I want the DateModified column to reflect the actual original document date modified time value (in example, i want the document datemodified same as what you see in windows explorer view) Is it possible to reflect the original document date modified value in document library? Please help. Thanks. Cheers SteveAnonymous
February 17, 2009
I have been trying for a few days to upload documents to SP. The only issue is that the code shouldn't run on the SP server and the development machine does not have SP installed, so we can't reference the library. I did find something on MSDN and it's simple. http://msdn.microsoft.com/en-us/library/cc514223.aspxAnonymous
February 20, 2009
Has anyone ever coupled a drag-n-drop to this so that rather than using a browse to find a file, the user can just drag it onto their web page.Anonymous
March 24, 2009
Hi All, Any one knows how to upload using a hashtable and also be able to specify the value of a "Person" type field Please adviseAnonymous
May 26, 2009
hello everyone... i'm new in sharepoint and ihave a lot of question, 1.how to change upload document path...?? 2.how to deactivated pulldown menu at shared document im not an expert here.... so pleaaasseeee guide me step by step... thanks a lotAnonymous
July 09, 2009
Im trying upload using windows explorer by using copy and paste method as we all use in general but for some users sharepoint is allowing to upload and for some who have the same permissions its not allowing.... Please help me........Anonymous
September 02, 2009
Ok, so how would I do this from Cygwin? And, no - I'm not joking.Anonymous
September 23, 2009
Hello Experts, i want to transfer documnets from MOSS server 1 to WSS server2 i.e. DocumentLibrary1(MOSS Server1) --->>DocLibrary2(WSS Server2). i tried CopyIntoItems()method of copy.asmx but no luck. can anyone please let me know is it possible programatically in sharepoint to copy documents from one server to another. Thanks in advance RamAnonymous
November 19, 2009
After some searching I found this on accessing sharepoint through VBA: http://msdn.microsoft.com/en-us/library/aa159897(office.11).aspxAnonymous
May 22, 2011
Hi i have try the code but appeare th enext error message: "The Web application at http://milsharep01/home.aspx could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application." The istruction where there is the error is: SPWeb site = new SPSite(destUrl).OpenWeb(); where is my mistakes? Thanks in advanceAnonymous
September 05, 2011
ya its a good article ,but this is not my requiremant . Actually my requirement is this things ti be done by prograamatically.......Anonymous
October 06, 2011
Could some one please elaborate on how to upload excel file to share point using excel vba...!!Anonymous
October 30, 2011
Document libraries are collections of files that you can share with team members on a Web based on Microsoft Windows SharePoint Services. For example, you can create a library of common documents for a project, and team members can use their Web browsers to find the files, read them, and make comments. Users with Microsoft Office 2003 can check out and edit the files as if they resided on a local or network drive. By default, your team Web site comes with a built-in document library named Shared Documents, which is listed on the Quick Launch bar as well as on the Documents and Lists page.