Friday 24 February 2017

Console App to Upload Documents in Document Library

String fileName = string.Empty ; String filePath ;

              filePath = System.Configuration.ConfigurationManager.AppSettings["Folderpath"].ToString();
    string[] filePaths = Directory.GetFiles(filePath);

         
         
    foreach (string filepath in filePaths)
    {
        Console.WriteLine(filepath);
        Console.ReadLine();
    using (SPSite oSite = new SPSite( Your Site name))
        {
            using (SPWeb oWeb = oSite.OpenWeb())
            {
                if (!System.IO.File.Exists(filepath))
                    throw new FileNotFoundException("File not found.", filepath);

                SPFolder myLibrary = oWeb.Folders[Libraryname];

                // Prepare to upload
                Boolean replaceExistingFiles = true;
                 fileName = System.IO.Path.GetFileName(filepath);
                 FileStream fileStream = System.IO.File.OpenRead(filepath);

                // Upload document
                SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);

                // Commit
                myLibrary.Update();
            }
        }
   



    }

No comments: