Showing posts with label Programatically publish document to document library. Show all posts
Showing posts with label Programatically publish document to document library. Show all posts

Tuesday, April 2, 2013

Easy but worth publishing.. Uploading document to Doc Library via Code..


 public static void PushFileToDocLib()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite("site url"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                       
                        string fileToUpload = "c:\\ExcelWorkBookName.xlsx";
                        if (!System.IO.File.Exists(fileToUpload))
                            throw new FileNotFoundException("File Not Found", fileToUpload);
                        SPFolder docLibrary = web.Folders["Document Lib Name"];
                        Boolean ExistingFiles = true;
                        string fileName = System.IO.Path.GetFileName(fileToUpload);
                        FileStream fileStream = File.OpenRead(fileToUpload);
                        SPFile spFile = docLibrary.Files.Add(fileName, fileStream, ExistingFiles);
                        docLibrary.Update();



                    }
                }
            });
        }