Tuesday, May 12, 2009

How to programmatically upload a document in a SPDocumentLibrary

In this post I discussed, how we can programmatically upload a document in a SPDocumentLibrary (SharePoint's document library).

Following method contains the logic to upload the document (codes with comments are self-explainatory).



/// <summary>
/// Programmatically UPLoad document in SPDocument Library
/// </summary>
void documentUploadInSPDocumentLibrary()
{
//fileUpload is ASP.Net FileUpload control.
if (!string.IsNullOrEmpty(fileUpload.FileName))
{
SPSite oWebsite = SPContext.Current.Web;
oWebsite.AllowUnsafeUpdates = true;
SPDocumentLibrary docLib
= oWebsite.Lists["DOCLIB_NAME"] as SPDocumentLibrary;

//Get file extension ( *.doc OR *.docx )
string fileExtension
= fileUpload.FileName.Substring(fileUpload.FileName.IndexOf("."));
byte[] fileBytes = fileUpload.FileBytes;
string destUrl
= docLib.RootFolder.Url + "/" + "MyFileName" + fileExtension;
SPFile destFile = docLib.RootFolder.Files.Add(destUrl, fileBytes, true);
destFile.Update();

oWebsite.AllowUnsafeUpdates = true;
}
}

3 comments:

Khushi said...

Hi Avinash.

I want to merge result of this article with one of your another article "Programmatically Export records from SPList to MS Excel"

So basically i am trying to do is
I need to create a document on the fly and upload into the document library.

The document could be word or Excel doesn;t matter and its contents are the result of some process that gives either SPLIst or Data Table.

how could i achieve actions of your two articles as a one process.

Please Suggest
Thanks
Khushi

Anonymous said...

Спасибо очень помогло

Anonymous said...

This is the code i neededfor asp.net and sharepoint. Thanks

Qing

Google