Visit our SharePoint Forum

SharePoint developer? Submit Yourself as Freelancer

Sunday, February 10, 2008

Programmatically Adding Documnets in Document Library

Brief:

By Creating a ASP.Net file uploload contol and a submit button. You can add documents and Files from your local folder,directly into Sharepoint Document library by using SPFile class.

Lets get Started:

1. Create a ASP.Net Webapplication , and Add a Fileupload Control in that.

2. Add a button named "Upload" under the Fileupload Control.


3. Now double click the Upload Button and write the Site collection and site reference as below.


4. And Finally, Call the DocumnetsAttached method on the submit click.

protected void Button1_Click(object sender, EventArgs e)
{

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
DocumnetsAttached(myWeb);
}

Make sure you add a reference to Microsoft.Sharepoint.dll.

//The Function for uploading a File in a Document Library is Below:

public void DocumnetsAttached(SPWeb site)
{
if (FileUpload1.HasFile)
{
SPFolder folder = site.GetFolder("Document_Library_Name");

SPFileCollection files = folder.Files;

Stream fStream = FileUpload1.PostedFile.InputStream; //path of the file to upload

byte[] contents = new byte[fStream.Length];

fstream.position =0;

fStream.Read(contents, 0, (int)fStream.Length);

fStream.Close();

string Filename = FileUpload1.FileName;

string URL = SPContext.Current.Site.Url + "/Document_Library_Name/" + Filename;

SPFile currentFile = files.Add(URL, contents);
}

}

2 comments:

Anonymous said...

Hey..Your Blog is covers all most topics of MOSS2007 and WSS 3.0.it's very nice blog.

All articles are well describe

Anonymous said...

Was wondering why not simply use the functionality built into the default SharePoint library webpart for uploading one or more files?

SharePoint Programming