How to Programmatically Upload files and folders to a SharePoint Document Library and Update and Delete Files from SharePoint Sites.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;


public partial class SharePoint : System.Web.UI.Page
{
    SPWeb mySite;

    // Declaring Private variable.         
    private string url;
    private string documentLibrary;

    // Extracting the data from web.config file for (URL and Document Library name).    
    protected void Page_Load(object sender, EventArgs e)
    {
        url = ConfigurationManager.AppSettings["SiteUrl"];
        documentLibrary = ConfigurationManager.AppSettings["Doclibrary"];
    }

    ///    
    /// FileUpload Event to upload the file on button click in sharepoint document library.   
    ///    
    /// give the name of the control which occur this event   
    /// indicate that the current event isn’t containing any event data.   
    protected void UploadFile_Click(object sender, EventArgs e)
    {
        if (InitializeSP())
        {
            Stream iStream = FileUpload1.PostedFile.InputStream;
            if (iStream.Length != 0)
            {
                string fname = GetName(true);

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

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

                    }
                }
                else
                {
                    Result.Text = "Document Library With a name MyFiles does not exists";
                }
            }
            else
            {
                Result.Text = "Cannot create Empty file";
            }
            mySite.AllowUnsafeUpdates = false;
        }
    }

    ///    
    /// FileDelete event which delete the file from sharepoint site document library.   
    ///    
    /// give the name of the control which occur this event   
    /// for indicating that the current event isn’t containing any event data.   
    protected void FileDelete_Click(object sender, EventArgs e)
    {
        bool fileExists = false;
        if (InitializeSP())
        {
            string fileName = GetName(true);
            if (mySite.GetFolder(documentLibrary).Exists)
            {
                SPFolder folder = mySite.GetFolder(documentLibrary);

                //Get the files from the document Library   
                SPFileCollection files = folder.Files;

                //If you dont know the url of file and have maintained only the id of file then    
                //Loop through all files to get the desired file and then get url from it.   
                for (int noOfFiles = 0; noOfFiles < files.Count; noOfFiles++)
                {
                    SPFile tempFile = files[noOfFiles];
                    //IdOfFileYouWantToDelete   
                    if (tempFile.Name.Equals(fileName, StringComparison.InvariantCultureIgnoreCase))// IdOfFileYouWantToDelete)   
                    {
                        folder.Files.Delete(tempFile.Url);
                        fileExists = true;
                        break;
                    }
                }
                Result.Text = string.Format("File {0} is deleted successfully", fileName);
                if (!fileExists)
                {
                    Result.Text = string.Format("File {0} not exists in Document Library", fileName);
                }
            }
            mySite.AllowUnsafeUpdates = false;
        }
    }


    ///    
    /// FolderUpload event which upload the folder in sharepoint site document library.   
    /// content of folder also get loaded.   
    ///    
    /// give the name of the control which occur this event   
    /// for indicating that the current event isn’t containing any event data.   
    protected void FolderUpload_Click(object sender, EventArgs e)
    {

        if (InitializeSP())
        {
            string fldName = GetName(false);

            if (Directory.Exists(FolderName.Text))
            {
                DirectoryInfo dirinfo = new DirectoryInfo(FolderName.Text);
                DirectoryTree(dirinfo);
                Result.Text = string.Format("Folder {0} uploaded successfully", fldName);
            }
            else
            {
                Result.Text = string.Format("Folder {0} does not exists on the local drive", fldName);
            }
        }

    }


    ///    
    /// Method for updating the file in sharepoint document library.   
    ///    
    /// give the name of the control which occur this event   
    /// for indicating that the current event isn’t containing any event data.   
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        if (InitializeSP())
        {
            string fileName = GetName(true);
            if (mySite.GetFolder(documentLibrary).Exists)
            {
                SPFolder folder = mySite.GetFolder(documentLibrary);
                SPFileCollection filecollection = folder.Files;

                if (CheckFileExists(filecollection, fileName))
                {
                    SPFile myFile = mySite.GetFolder(documentLibrary).Files[fileName];
                    Stream fs = FileUpload1.PostedFile.InputStream;

                    if (fs.Length > 0)
                    {
                        byte[] localData = new byte[fs.Length];
                        fs.Read(localData, 0, localData.Length);
                        byte[] binFile = new byte[localData.Length + myFile.Length + 1];

                        (myFile.OpenBinary()).CopyTo(binFile, 0);
                        binFile[myFile.Length] = Convert.ToByte('\n');
                        localData.CopyTo(binFile, myFile.Length + 1);

                        myFile.SaveBinary(binFile);
                        myFile.Update();
                        Result.Text = string.Format("File {0} updated successfully", fileName);
                    }
                    else
                    {
                        Result.Text = "Local file U choose is empty nothing to update";
                    }
                }
                else
                {
                    Result.Text = string.Format("File {0} does not exists in sharepoint site", fileName);
                }
            }
            else
            {
                Result.Text = string.Format("Document library {0} does not exists", documentLibrary);
            }
            mySite.AllowUnsafeUpdates = false;
        }
    }


    ///    
    /// Method for checking the file exists in the sharepoint site document library.    
    ///    
    /// contains collection of files   
    /// name of the file to be check of   
    /// bool value   
    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))
            {
                Result.Text = string.Format("File {0} already exists ", name);
                fileExists = true;
                break;
            }
        }
        return fileExists; //return bool values depends upon the file check.   
    }

    ///    
    /// Intiliaze the site and give the permission to do the updates  in the sites.     
    ///    
    private bool InitializeSP()
    {
        bool isSiteExists = false;
        if (url != null)
        {
            if (mySite == null)
            {
                try
                {
                    mySite = new SPSite(url).OpenWeb();
                    mySite.AllowUnsafeUpdates = true;
                    isSiteExists = true;
                }
                catch (FileNotFoundException)
                {
                    Result.Text = string.Format(" Url {0}  not found ,check the URL you have Given", url);
                    return isSiteExists;
                }
            }
            else
            {
                Result.Text = string.Format(" Url {0}  not found ,check the URL you have Given", url);
            }
        }
        else
        {
            Result.Text = "Please specify the site url in config file.";
        }

        return isSiteExists;
    }

    ///    
    /// Recursive method for checking all folders in a folder and all files in the folders .   
    ///    
    /// Name of the folder   

    void DirectoryTree(DirectoryInfo root)
    {
        FileInfo[] files = null;
        DirectoryInfo[] subDirs = null;


        if (Directory.Exists(root.FullName.ToString()))
        {
            //DirectoryInfo dirinfo = new DirectoryInfo(path);   
            SPFolder folder = mySite.GetFolder(documentLibrary);
            SPFolderCollection folderCollection = folder.SubFolders;
            SPFolder AddedFolder = folderCollection.Add(root.FullName.Substring(3));

            // First, process all the files directly under this folder   
            try
            {
                files = root.GetFiles("*.*");
            }
            catch (DirectoryNotFoundException ex)
            {
                Result.Text = "ERROR: Missing some Files :" + ex.ToString();
            }

            if (files != null)
            {
                for (int noOfFiles = 0; noOfFiles < files.Length; noOfFiles++)
                {
                    FileStream fStream = File.OpenRead(root.FullName.ToString() + "\\" + files[noOfFiles].Name);
                    byte[] content = new byte[fStream.Length];
                    int c = fStream.Read(content, 0, (int)fStream.Length);
                    fStream.Close();
                    AddedFolder.Files.Add(files[noOfFiles].Name, content);
                }

            }

            // Now find all the subdirectories under this directory.   
            subDirs = root.GetDirectories();

            foreach (DirectoryInfo dirInfo in subDirs)
            {
                // Resursive call for each subdirectory.                   
                DirectoryTree(dirInfo);
            }
        }
        else
        {
            Result.Text = "Directory path not exists";
        }
    }

    // FolderName is the ID of the textbox. 
    // FileUpload1 is the iD of the fileupload control    
    private string GetName(bool FileOrFldName)
    {
        if (!FileOrFldName)
        {
            int nameStart = FolderName.Text.LastIndexOf(@"\");
            string fName = FolderName.Text.Substring(nameStart + 1);
            return fName;
        }
        else
        {
            int basenamestart = FileUpload1.PostedFile.FileName.LastIndexOf(@"\");
            string fName = FileUpload1.PostedFile.FileName.Substring(basenamestart + 1);
            return fName;
        }

    }
}


Tags: ,
Permalink | Comments (0) | Post RSSRSS comment feed