Home Contact

The Frog Pond of Technology

Ripples of Knowledge for SharePoint and Other .Net Technologies

News

My blog has moved to WordPress at BrianTJackett.com. Any pages will automatically redirect to the new address in 7 seconds. Please excuse an issues during this migration.

 Subscribe to this blog


About Me

Name:
Brian T. Jackett
Location:
Columbus, OH
Company:
Microsoft

Find me on...

Tag Cloud


Article Categories

Archives

Post Categories

Syndication:

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:\temp\myFileToUpload.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


Monday, February 15, 2010 9:25 PM

Feedback

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Thanks Alot........... 4/15/2010 1:30 AM | kusuma

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

I'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 LONG
Can U Help Me? 5/3/2010 6:01 AM | Marco Guidone

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Marco,

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 5/3/2010 8:21 AM | Brian Jackett

# re: Programmatically Uploading Files To A SharePoint 2010 Document Library

I 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? 8/11/2010 12:25 PM | don

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Don,

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. 8/11/2010 11:52 PM | Brian T. Jackett

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Don,

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.
9/25/2010 11:36 AM | Brian T. Jackett

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Hello,

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! 10/25/2010 9:50 AM | Scott

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Scott,

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.
10/26/2010 9:08 AM | Brian Jackett

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

i getting below erroe when i run the above code

System.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. 3/21/2011 6:47 AM | James

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Recently 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 12/20/2011 2:41 PM | Jim Doyle

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Smith,

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.
12/20/2011 9:51 PM | Brian T. Jackett

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

first uploading a byte array representation of a string and second for uploading a file. 12/24/2011 4:15 AM | x ray tech

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Permission settings or Services not configured correctly. Any ideas? 12/31/2011 12:58 AM | captain

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Is there a way to add metadata to the document that is being uploaded? 1/6/2012 4:56 PM | Joe

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Joe,

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.
1/9/2012 11:56 PM | Brian T. Jackett

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

I 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. 2/17/2012 12:34 AM | Jitendra Masand

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Thanks 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. 3/1/2012 11:17 AM | Abhi

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Thanks 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 :-) 4/13/2012 11:31 AM | Rob

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Rob,

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.
4/16/2012 11:23 AM | Brian T. Jackett

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Hi,

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. 1/17/2014 7:29 AM | Kamakshi

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Hi,

The remote server returned an error: (407) Proxy Authentication Required.

Can someone help me on this. 1/17/2014 7:30 AM | Kamakshi

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Kamakshi,

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.
1/23/2014 1:20 PM | Brian T. Jackett

# re: Uploading a string (converted to file) to a document library

I 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 ? 6/3/2014 10:29 AM | Sylvie

# re: Programmatically Uploading Files To A SharePoint 2007 Document Library

Long 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.
6/4/2016 2:58 PM | Roksolana

Post A Comment
Title:
Name:
Email:
Comment:
Verification: