Uploading files to a SharePoint document library through the web UI is a fairly simple process, but did you know it’s also possible to programmatically upload a file (or string) to a document library? Over the past two weeks I’ve had the latter scenario come up with friends and coworkers in several separate instances so I thought I’d post some simple code snippets on how to accomplish this. I can’t take all credit as I borrowed the base code for uploading from a project my coworker Kelly Jones and I are on. Below are two code snippets for first uploading a byte array representation of a string and second for uploading a file.
Uploading a string (converted to file) to a document library
string textToOutput = "Some text I want to put out to a file";
string uploadPath = "<URL for your document library + filename>";
// ex. http://server/myDocLib/SomeFile.csv
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] bytesToOutput = encoder.GetBytes(textToOutput.ToString());
using (WebClient client = new WebClient())
{
client.Credentials = System.Net.CredentialCache.DefaultCredentials;
client.UploadData(uploadPath, "PUT", bytesToOutput);
}
Uploading a file to document library
string localFilename = "<path to file you wish to upload>";
// ex. c:tempmyFileToUpload.doc
FileStream myStream = new FileStream(localFilename, FileMode.Open, FileAccess.Read);
BinaryReader myReader = new BinaryReader(myStream);
byte[] bytesToOutput = reader.ReadBytes((int)myStream.Length);
myReader.Close();
myStream.Close();
using (WebClient client = new WebClient())
{
client.Credentials = System.Net.CredentialCache.DefaultCredentials;
client.UploadData(uploadPath, "PUT", bytesToOutput);
}
Conclusion
Programmatically uploading a file to a SharePoint document library is actually a fairly simple process as seen by the short code snippets above. The basic premise is that you are performing an HttpRequest Put operation with the byte array representation of either a file or a string. I’ve used this on a number of occasions at one of my current clients and it’s been very helpful. Feel free to leave feedback if you found this helpful, have any questions, or suggestions for improvement.
-Frog Out
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#515334Thanks Alot………..
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#517725I’ve try to use your code but I’ve got an error: Unable to upload file (WebException) :- Message : The remote server returned an error: (414) REQUEST URI TOO LONG.- Response : System.Net.HttpWebResponse- Status : ProtocolError- Status Code : RequestUriTooLong- Status Description : REQUEST URI TOO LONGCan U Help Me?
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#517756Marco, How long is the upload path that you are attempting to upload to? It sounds like the HttpRequest may be failing because your upload path is too long. If not that then the size of data (byte array) might be too large and being rejected by SharePoint. The default file size limit is 50 MB, but that can be configured higher if needed as long as you are ok with the associated performance hit. See the below link for additional details on 414 errors.http://www.checkupdown.com/status/E414.html
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#532583I used this method without problems for 2 years on sharepoint 2007.we recently migrated to sharepoint 2010.no this does not work. I get no errors or exceptions at all (as though it works) but when i look into document library – NO FILE!No errors! NO FILE.Why has this suddenly start occuring on sharpoint 2010?ANy IDEAS?
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#532663Don, I have not attempted to port this solution to SharePoint 2010. I am busy with planning SharePoint Saturday Columbus which is happening this weekend, but the next chance I get I’ll try this out on SharePoint 2010 and let you know what I find. Thanks for the feedback.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#539725Don,Sorry for the long delay. I finally got around to testing out this code on SharePoint 2010 and it was successful. There are a few things that you’ll want to check for troubleshooting.First, ensure that the account executing your code has access to the site and list that you are accessing.Second, ensure the URL you are using is correct for the list. I tried the first method with specifying the filename and uploading a piece of text.Third, check your logs (event log and ULS) to see if there are any errors being thrown regarding your code.Let me know if you have any success or further questions. Thanks.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#544401Hello,Thank you for the above code snippet. I’m having some trouble getting it to work and am thinking it has more to do with my configuration rather than the code. I’m on sharepoint 2007 running on windows server 2008 and I get the the following error message:”The remote server returned an error: (405) Method Not Allowed” when trying to execute this code. any thoughts on where I’m going wrong? any help would be greatly appreciated!
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#544614Scott, It does sound like you have a configuration or security restriction preventing you from performing a POST operation. Check IIS Manager under the site you are hitting and make sure you have ASP.Net 2 allowed under extensions. Also do you have any custom settings in your web.config or machine.config that prevent server side scripting? Lastly do you have a Code Access Security (CAS) policy in place that limits what functionality can be accessed by this web application?Let me know if any of those help. Good luck.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#569382i getting below erroe when i run the above codeSystem.Net.WebException was unhandled by user code Message=The remote server returned an error: (401) Unauthorized. Source=System StackTrace: at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request) at System.Net.WebClient.UploadData(Uri address, String method, Byte[] data) at SpfileUpload.Layouts.SpfileUpload.Upload.button1_Click(Object Sender, EventArgs e) at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) InnerException:help me out Thanks in advance.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#603320Recently installed WSS 3.0 running on Windows 7. Everything installed ok, however a custom app that we use for Document Capture and Upload to SP returns error: “Error uploading document : The remote server returned an error: (405) Method Not Allowed. at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)”This works fine with Sharepoint 2007 and 2010. Suspect it is something to do with Security / Permission settings or Services not configured correctly. Any ideas?Thanks in advance.Jim
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#603335Smith, Does the file you are attempting to upload contain data? SharePoint will not allow you to upload a document if it contains no data. If that is not the issue can you get the HTTP status code of the web request response?Jim, Are you saying that you get the error only on your WSS 3.0 machine running Windows 7? While it may be possible to run WSS 3.0 on Windows 7 I wouldn’t recommend it is a true development or testing platform due to a number of items that just don’t work like they do on a server OS. I’m told that 405 errors typically originate from configuration settings in the web.config file. That might be a good place to start comparing against a known working environment.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#603754first uploading a byte array representation of a string and second for uploading a file.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#604416Permission settings or Services not configured correctly. Any ideas?
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#604945Is there a way to add metadata to the document that is being uploaded?
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#605169Joe,Using the method I outlined above you can not add metadata (that I know of). It would be possible to upload the file, get a reference to the new SPListItem, and then edit the metadata on that though.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#608085I want to upload file from my aspx application to sharepoint. When i run the application from my local macine it works fine and the file gets uploaded. However when i publish the websites and run it from the server it gives error “Unauthorized 401”. Tried everything but it is not working. Please advice.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#609200Thanks a lot! This worked like a charm. I had the exact same requirement from our customers to get the list data and convert into a CSV file. One of the other applications needed this file to consume and I was able to upload it into the library.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#611927Thanks for this brilliant peace of code. Do you know how to show the control to upload multiple files on a custom web part or an application page? I mean your programme above, how will it get files from?Thanks for your help 🙂
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#612068Rob,The above code was placed into a console application and had some Windows Forms code to show a file picker. I do not have the code any longer though as it was for a customer from years ago.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#635054Hi,I am trying to upload file to Sharepoint 2010 using the above code and I keep getting the error as below:The remote server returned an error: (407) Proxy Authentication Required.Can someone help me on this.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#635055Hi,The remote server returned an error: (407) Proxy Authentication Required.Can someone help me on this.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#635222Kamakshi,Looking at the error message it sounds like your network traffic goes through a proxy. On the System.Net.WebClient variable that you create you can specify credentials for the proxy. I have not used this personal but give that a try.
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#638158I will try to do that but I always have 504 gateway timeout error. I have installed sharepoint foundation locally and I have the same error. Do you know why ?
LikeLike
Originally posted on: https://briantjackett.com/archive/2010/02/15/programmatically-uploading-files-to-a-sharepoint-2007-document-library.aspx#650149Long Path Tool help me a lot when i have an issue like file deleting or renaming the file. Also good to use if file name and file extension is too long.
LikeLike