We are exploring SharePoint 2007 from last few days. Here is the code for adding new document to document library using C#. I have created a page with a file upload control and a button. When user clicks on button the selected document will be uploaded to specific document library. You need to add reference to Microsoft.SharePoint DLL to make this code running.
if (FileUpload1.PostedFile != null)
{
if(FileUpload1.PostedFile.ContentLength > 0)
{
System.IO.Stream strm =
FileUpload1.PostedFile.InputStream;
byte[] byt = new byte[
Convert.ToInt32 (
FileUpload1.PostedFile.ContentLength)];
strm.Read(byt, 0, Convert.ToInt32
(FileUpload1.PostedFile.ContentLength));
strm.Close();
// Open site where document library is created.
using (SPSite objSite = new SPSite
("http://server:port/"))
{
using (SPWeb objWeb = objSite.OpenWeb())
{
SPFolder mylibrary = objWeb.Folders["Name of
Document Library"];
// Set AllowUnsafeUpdates = true to avoid
// security error
objWeb.AllowUnsafeUpdates = true;
mylibrary.Files.Add(System.IO.Path.GetFileName
(FileUpload1.PostedFile.FileName), byt);
}
}
}
}
Above code first reads the uploaded file in Stream and than uploads it on document library.
Happy Programming !!!
No comments:
Post a Comment