Thursday, April 18, 2013

[SharePoint] Upload File To Document Library Using SharePoint Object Model - Authenticate or Anonymous Access



using Microsoft.SharePoint;    //SharePoint
using System.IO;                //Stream

//if  Anonymous Access, document library must set to allow anonymous to add items
string strSharePointURL = "http://www.sharepoint.com";

if (txtUpload.HasFile)
{
    if (txtUpload.PostedFile.ContentLength > 0)
    {
        //string strFileName = txtUpload.PostedFile.FileName;
        string strFileName = txtUpload.FileName;

        Stream fStream = txtUpload.PostedFile.InputStream;
        byte[] bStream = new byte[fStream.Length];
        fStream.Read(bStream, 0, bStream.Length);
        fStream.Close();

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite objSite = new SPSite(strSharePointURL))
            {
                using (SPWeb objWeb = objSite.OpenWeb())
                {
                    SPFolder libraryFolder = objWeb.Folders["Document_Library_Name"];
                    objWeb.AllowUnsafeUpdates = true;

                    libraryFolder.Files.Add(strFileName, bStream, true);
                }
            }
        });
    }
}
//In html code
<asp:FileUpload runat="server" id="txtUpload"/>

No comments:

Post a Comment