How to upload a document in a document library programmatically

Recently I have encountered in a situation where I was required to upload few documents in a document library using my code. I found this fairly simple. Thanks to object model exposed by Microsoft.

Following code can be use to upload a document to document library with in specific site.

SPSite mySite = new SPSite("http://");

SPWeb spWeb = mySite.OpenWeb();

SPDocumentLibrary docLib = (SPDocumentLibrary) spWeb.Lists[""];

SPFolder folder = docLib.RootFolder;
using( FileStream fs = File.OpenRead("" ) )
{
SPFile file= folder.Files.Add("",fs);
file.Update();
}


I hope this will be helpful for those who wants to update documents and also needs to perform few custom actions on uploaded documents.

Comments

Popular posts from this blog

IIS Configuration Error Error: Cannot write configuration file due to insufficient permissions

Using content query web part

STSAdm AddSolution - Failed to extract the cab file