Wednesday, April 25, 2012

How To Upload file Into a SharePoint Document Library
[Upload file programmatically into given folder path ]
(Data Migration P2)


This is directly bind with the previous post (How To Create Folder Structure in SharePoint Document Library) . There I explained that I got a task on Data Migration move file from master file share into SharePoint Site. there i had to consider on two different sub task mainly

  1. How to create folder structure which same as physical path of the file (which I explained in Data Migration P1)
  2. How to upload the required document form file base to that newly created location in the document library (which I'm going to explain in Data Migration P2)

The Requirement ....

Original file : C:\swsetup\SP51083\Vista\example.docx

SharePoint Location :http://talliance.domainx.local:12345/DocLibName/swsetup/SP51083/Vista/


highlighted area represent the directory path which they need to upload the file (I have discussed how to create this inside the document library)
highlighted area represent the document library which they need to upload the file.


How to do that ?? 


For this I have introduce a function which responsible to upload the required file into the correct location.


spServerURL : The URL of the application [Eg: http://myspweb:8000/]

spDocumenttargetUrl :  the name of the document library which you need to upload documents 

folder : location of the doc lib which need to upload our file

FileToUpload : the physical location of the file which need to upload (Eg : C:\swsetup\SP51083\Vista\example.docx)


Overwirte : saying where file should be overwrite, if it existing or leave it as it is.  



public static void CreateSPFile(string spServerURL, string spDocumenttargetUrl, string folder, string fileToUpload, bool overwrite)
        {
            // I suggest skip this pre check since it internally opens a new site object
            // If you have to silenlty ignore non-existant SPSite you should catch a FileNotFoundException.
            if (SPSite.Exists(new Uri(spServerURL)))
            {
                // use the using construct to safely dispose the opened SPSite object
                using (SPSite site = new SPSite(spServerURL))
                {
                    // SPWeb object opened with SPSite.OpenWeb() have to be disposed as well
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;

                        string targetUrl = string.Concat("\\", spDocumenttargetUrl);

                        if (!String.IsNullOrEmpty(folder))
                        {
                            targetUrl = string.Concat(targetUrl + folder);
                        }

                        SPFolder target = web.GetFolder(targetUrl);
                        String fileName = System.IO.Path.GetFileName(fileToUpload);
                        FileStream fileStream = File.OpenRead(fileToUpload);
                        SPFileCollection files = target.Files;
                        target.Files.Add(fileName, fileStream, overwrite);

                    }
                }
            }
        }

Let's Move from Line by Line ....
I'm gonna explain, only the most important lines in this function.

SPWeb web = site.OpenWeb()
web.AllowUnsafeUpdates = true;


when you have a list and if you want to update something, then you need to set AllowUnsafeUpdates = true for the web and the best practice is, after you have done you need to set it back to false. but in here i haven't make it false coz this process going through a massive loop so it'take time and might be crashed. and also "Setting this property to true opens security risks, potentially introducing cross-site scripting vulnerabilities" (by msdn).

string targetUrl = string.Concat("\\", spDocumenttargetUrl);

                        if (!String.IsNullOrEmpty(folder))
                        {
                            targetUrl = string.Concat(targetUrl + folder);
                        }
Crete target folder URL by combining Folder location and document library relative URL
    

String fileName = System.IO.Path.GetFileName(fileToUpload);
                        FileStream fileStream = File.OpenRead(fileToUpload);

Convert the physical file into the data stream which we are going to add into the required location.

SPFileCollection files = target.Files;
Get the file collection on the target location.

target.Files.Add(fileName, fileStream, overwrite);
Add the stream into the required location.




 ok That's It ... 
HAPPY CODING

How To Create Folder Structure in SharePoint Document Library
[File structure which same to the physical path]
(Data Migration P1)

I was assigned for a data migration task in one of a project. in that project client has a aster file based which hold more that 50,000 files like excel doc and pdf. what he need it upload them into the SharePoint site using console application.
requirement is quite complex so in that case I divided it into 3 parts and will share the things which I think that it'll useful for you also.
Why we need folder structure ?? 
this is not just a data migration we need to create folder path which exactly same to the physical  path of the file which required to migrate. please refer the attachment, below to get a better understanding.

when you consider the yellow highlighted area you can see that the physical file path should be same means inside the document library we need to create [Settlement System -> CES Inputs -> 2011 -> Dawn Gas Prices] directory structure.

How to do that ?? 
to do that I have introduce a function which can create this folder structure.

spServerURL : The URL of the application [Eg: http://myspweb:8000/]

spDocumentLibraryName :  the name of the document library which you need to upload documents or create folder path on top of [Eg : Settlement (which highlighted on blue in above picture)

Filepath : physicle file path of the document (Eg : C:\ThilinaLIB\SAMPLES\Cost and Production\5 Minute Meter Data\File Names - AG and MW - Copy (4).xlsx)

Removablepath : path which remove (no use for migration which highlighted in gray color in above picture) [Eg: C:\ThilinaLIB]




public static void CreateFolder(string spServerURL,string spDocumentLibraryName,string FilePath,string Removablepath)
        {

            try
            {
                SPSite _MySite = new SPSite(spServerURL);
                SPWeb _MyWeb = _MySite.OpenWeb();
                // create document lib object which we use for uploading and creating folder paths
                SPDocumentLibrary _MyDocLibrary = (SPDocumentLibrary)_MyWeb.Lists[spDocumentLibraryName];
                SPFolderCollection _MyFolders = _MyWeb.Folders;
                // create folder path which we need to manipulate inside the document library
                FilePath = FilePath.Replace(Removablepath, "");

                char[] directoryCharSeparators = new char[] { Path.DirectorySeparatorChar };
                string mypath = Path.GetDirectoryName(FilePath);
                // Get the folder structure.
                string[] directories = mypath.Split(directoryCharSeparators, StringSplitOptions.RemoveEmptyEntries);
                // cretae document lib path
                string Target = SPUrlUtility.CombineUrl(_MyWeb.ServerRelativeUrl, spDocumentLibraryName);

                foreach (string item in directories)
                {
                    Target = Target + "/" + item;
                    _MyFolders.Add(Target + "/");
                }
                // folder creation is completed in this point
                _MyDocLibrary.Update();
                           }
            catch (Exception ex)
            {
               
                throw ex;
            }
        }

Let's Move from Line by Line ....
SPDocumentLibrary _MyDocLibrary = (SPDocumentLibrary)_MyWeb.Lists[spDocumentLibraryName];
create document library object which we are going to use to create our folder structure.


SPFolderCollection _MyFolders = _MyWeb.Folders;
Take the existing folder collection. which we are using to add our new folders.


FilePath = FilePath.Replace(Removablepath, "");
This is so important. we need to remove some of part form the original file path. Imaging if the file path is like this "C:\TEMP\SP4RK\compmgmt\compadmn\example.xlsx" but we are going to create folder structure in the document library as following "http://talliance.domainx.local:12345/Settlement/SP4RK/compmgmt/compadmn/" so we need to remove "C:\TEMP" part from the original file path.


string mypath = Path.GetDirectoryName(FilePath);
get only directory or Folder path. Eg : if FilePath = "\SP4RK\compmgmt\compadmn\example.xlsx" The myPath would be "\SP4RK\compmgmt\compadmn"


char[] directoryCharSeparators = new char[] { Path.DirectorySeparatorChar };
                // Get the folder structure.
                string[] directories = mypath.Split(directoryCharSeparators, StringSplitOptions.RemoveEmptyEntries);


Use to take directory names in to the string array in a order so it's like directories = { "SP4RK","compmgmt","compadmn" }

string Target = SPUrlUtility.CombineUrl(_MyWeb.ServerRelativeUrl, spDocumentLibraryName);
we need to create target location which we are going to add the folders. it would be "\Settlement"


foreach (string item in directories)
                {
                    Target = Target + "/" + item;
                    _MyFolders.Add(Target + "/");
                }

This is the most important part using this loop we can create folder path one by one. (FYI: keep one thing in your mind you cannot create full folder path at once means to create  "compadmn" folder ,"SP4RK/compmgmt" should exist and do not worry is one folder is already exsiste and it it contain document inside those will remain even you create same folder again )

 _MyDocLibrary.Update();
Finally you should update the document library.


ok That's It ... 
HAPPY CODING