Programmatically Uploading Files To A SharePoint 2007 Document Library

    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

24 thoughts on “Programmatically Uploading Files To A SharePoint 2007 Document Library

  1. 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?

    Like

  2. 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

    Like

  3. 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?

    Like

  4. 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.

    Like

  5. 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!

    Like

  6. 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.

    Like

  7. 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.

    Like

  8. 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

    Like

  9. 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.

    Like

  10. 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.

    Like

Leave a comment