Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Tuesday, March 13, 2012

Simple Code Programatically Uploading a Document to a Document Library Via Object Model.



  

try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                 {
                    if (fuBrowse.PostedFile != null && fuBrowse.PostedFile.ContentLength > 0)
                    {
                        SPWeb web = SPContext.Current.Web;
                        HttpPostedFile myFile = fuBrowse.PostedFile;
                        int filelen = myFile.ContentLength;
                        byte[] contents = new byte[filelen];
                        myFile.InputStream.Read(contents, 0, filelen);
                        String fileName = System.IO.Path.GetFileName(fuBrowse.PostedFile.FileName);
                        string strFilenName = fileName;
                        Boolean replaceExistingFiles = true;
                        SPFile fileDetails = null;
                        SPFolder myLibrary = web.GetFolder("Shared Documents");
                        fileDetails = myLibrary.Files.Add(strFilenName, contents, replaceExistingFiles);
                        fileDetails.Update();
                        lblErrorMessage.Text = "Document Uploaded Successfully...!";
                    }
                });
            }
            catch (Exception ex)
            {

                lblErrorMessage.Text = ex.ToString();
            }



No comments:

Post a Comment