Tuesday, April 6, 2010

Upload a document into SharePoint library programmatically

Its very simple and straight forward. Steps are

1. Get instance of site using SPSite class
2. Get Instance of web using SPWeb class
3. Get the Library instance using SPFolder class, where you want to upload document.
4. Get the file to be uploaded.
5. Get the FileStream of the file to be uploaded.



public void publishDocumentToSharepoint(string filename)
{
string fileToUpload = "D:\\temp\\" + filename;
using (SPSite objSite = SPContext.Current.Site)
{
using (SPWeb objWeb = objSite.OpenWeb())
{
if (System.IO.File.Exists("D:\\temp\\" + filename))
{
SPFolder mylibrary = objWeb.Folders["Project Documents"];
Boolean replaceExistingFile = true;
string fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
objWeb.AllowUnsafeUpdates = true;
SPFile spfile = mylibrary.Files.Add(fileName, fileStream, replaceExistingFile);
mylibrary.Update();
fileStream.Close();
fileStream.Dispose();
objWeb.AllowUnsafeUpdates = false;
}
}
}



}



Questions/queries/suggestions are welcome.

Thanks
Sanjay Tiwari

No comments: