Looking for something?

Author: Tobias Zimmergren
URL: http://www.zimmergren.net


I’ve been getting a couple of requests to provide details on how you can upload a file or document using the SharePoint Object Model, instead of using the UI.

With this simple article, I’m walking you through the process of uploading any file to your Document Library.

Note; Since this is done through the local API, you need to have this code running on the server. That means that it’s ideal to use in for example a FeatureReceiver or EventReceiver. You cannot run this code on the client in e.g. a Windows Form, then you’ll need to utilize the SharePoint WebServices instead.

Code to upload a file/document to a SharePoint Document Library

Use the following code to get you started in uploading a file using the object model. It really isn’t that hard :-)

// Getting a reference to the document library var sp = new SPSite("http://localhost");;) var site = sp.OpenWeb(); var folder = site.GetFolder("Documents"); var files = folder.Files;

// Opening a filestream var fStream = File.OpenRead("C:MyDocument.docx"); var contents = new byte[fStream.Length]; fStream.Read(contents, 0, (int)fStream.Length); fStream.Close();

// Adding any metadata needed var documentMetadata = new Hashtable {{"Comments", "Hello World"}};

// Adding the file to the SPFileCollection var currentFile =     files.Add("Documents/MyDocument.docx", contents, documentMetadata, true);

site.Dispose(); sp.Dispose();

As you can see in the image below, the metadata "Comments" has been filled in as per the metadata I specified in the code above.

File uploaded using the Object Model

Simple as that. Over and out!

Technorati Tags: SharePoint,SPFile,SPFolder,SPSite,SPWeb,Document Library

0 Comments 18 April 2009
Tobias Zimmergren

Tobias Zimmergren

Hi, I'm Tobias. I am a Microsoft MVP for SharePoint and I use this site to share my thoughts on tech with you on topics like SharePoint, Office 365, Azure and general web development.

  Malmö, Sweden

Related Post

Comments powered by Disqus