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.

Friday, March 02, 2012

Programatically Uploading a document to SharePoint Document Library using SharePoint Object Model Perfectly



using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Security;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.IO;
using System.Data;
using System.Collections;
[assembly:AllowPartiallyTrustedCallers]
namespace UploadDocListItem
{
    [Guid("c7d6cdce-9379-4e34-887b-f7b0717a973b")]
    public class UploadDocListItem : System.Web.UI.WebControls.WebParts.WebPart
    {
        SPWeb mySite;

        // Declaring Private variable.       
        private string url;
        private string documentLibrary;
        FileUpload fuBrowse;
        TextBox txtUserName;
        TextBox txtPassWord;
        Button btnSave;
        byte[] contents;
        string strError = string.Empty;
        public UploadDocListItem()
        {
        }
        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write(strError);
            try
            {
                txtUserName.RenderControl(writer);
                txtPassWord.RenderControl(writer);
                fuBrowse.RenderControl(writer);
                btnSave.RenderControl(writer);
            }
            catch (Exception ex)
            {

                strError += ex.ToString();
            }
        }
        protected override void CreateChildControls()
        {
            try
            {
                txtUserName = new TextBox();
                txtUserName.ID = "txtUserName";
                this.Controls.Add(txtUserName);

                txtPassWord = new TextBox();
                txtPassWord.ID = "txtPassWord";
                this.Controls.Add(txtPassWord);

                fuBrowse = new FileUpload();
                fuBrowse.ID = "fuBrowse";
                this.Controls.Add(fuBrowse);

                btnSave = new Button();
                btnSave.ID = "btnSave";
                btnSave.Text = "Save Record";
                btnSave.Click += new EventHandler(btnSave_Click);
                this.Controls.Add(btnSave);

            }
            catch (Exception ex)
            {

                strError += ex.ToString();
            }
        }


        void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWeb currentweb = SPContext.Current.Web;
                    SPList lst = currentweb.Lists["Login"];
                    SPListItemCollection myColl = lst.Items;
                    SPListItem item = myColl.Add();

                    item["Title"] = txtUserName.Text;
                    item["PassWord"] = txtPassWord.Text;
                    if (fuBrowse.PostedFile != null && fuBrowse.PostedFile.ContentLength > 0)
                    {
                        System.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;
                        item["DocumentName"] = currentweb.Url + "/Shared Documents/" + strFilenName+", "+strFilenName;
                    }
                    item.Update();
                    if (InitializeSP())
                    {
                        Stream iStream = fuBrowse.PostedFile.InputStream;
                        if (iStream.Length != 0)
                        {
                            string fname = GetName(true);

                            if (mySite.GetFolder("Shared Documents").Exists)
                            {
                                SPFolder Folder = mySite.Folders["Shared Documents"];
                                SPFileCollection destFiles = mySite.GetFolder("Shared Documents").Files;

                                if (!CheckFileExists(destFiles, fname))
                                {
                                    try
                                    {
                                        Folder.Files.Add(fname, iStream);
                                        strError += string.Format("File {0} uploaded successfully", fname);
                                    }
                                    catch (Exception ex)
                                    {
                                        strError += "Error in adding the folder to the sharepoint site" + ex.ToString();
                                    }

                                }
                            }
                            else
                            {
                                strError += "Document Library With a name MyFiles does not exists";
                            }
                        }
                        else
                        {
                            strError += "Cannot create Empty file";
                        }
                    }
                   mySite.AllowUnsafeUpdates = false; 
                 strError+="Saved Successfully";
                });
               
            }
            catch (Exception ex)
            {

                strError += ex.ToString();
            }
       
        }
        private bool InitializeSP()
        {
            url = SPContext.Current.Web.Url;
            bool isSiteExists = false;
            if (url != null)
            {
                if (mySite == null)
                {
                    try
                    {
                        mySite = new SPSite(url).OpenWeb();
                        mySite.AllowUnsafeUpdates = true;
                        isSiteExists = true;
                    }
                    catch (FileNotFoundException)
                    {
                        strError += string.Format(" Url {0}  not found ,check the URL you have Given", url);
                        return isSiteExists;
                    }
                }
                else
                {
                    strError += string.Format(" Url {0}  not found ,check the URL you have Given", url);
                }
            }
            else
            {
                strError += "Please specify the site url in config file.";
            }

            return isSiteExists;
        }
        private string GetName(bool FileOrFldName)
        {
            if (!FileOrFldName)
            {
                int nameStart = fuBrowse.PostedFile.FileName.LastIndexOf(@"\");
                string fName = fuBrowse.PostedFile.FileName.Substring(nameStart + 1);
                return fName;
            }
            else
            {
                int basenamestart = fuBrowse.PostedFile.FileName.LastIndexOf(@"\");
                string fName = fuBrowse.PostedFile.FileName.Substring(basenamestart + 1);
                return fName;
            }

        }
        private bool CheckFileExists(SPFileCollection destFiles, string name)
        {
            bool fileExists = false;
            for (int noOfFile = 0; noOfFile < destFiles.Count; noOfFile++)
            {
                SPFile tempFile = destFiles[noOfFile];

                if (tempFile.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
                {
                    strError += string.Format("File {0} already exists ", name);
                    fileExists = true;
                    break;
                }
            }
            return fileExists; //return bool values depends upon the file check. 
        }
    }
}


No comments:

Post a Comment