Search This Blog

Wednesday, November 18, 2015

How to Programmatically Upload File to SharePoint Document Library?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.IO;
using System.Collections;
 
namespace UploadFiles
{
    class Program
    {
      static void Main(string[] args)
        {
          //Get the Site collection
            using (SPSite site = new SPSite("http://sharepoint.com"))
            {
                //Open the Root web
                using(SPWeb web=site.OpenWeb())
               {
                /*** Simple File Upload ********/
                // Read the file from the stream into the byte array
                FileStream fs= File.OpenRead(@"c:\MyDoc.doc");
                byte[] FileContent= new byte[fs.Length];
                fs.Read(FileContent, 0, Convert.ToInt32(fs.Length));
                fs.Close();
                //Get the documents Librarym named "Documents"
                SPList DocLib = web.Lists["Documents"];
                //Add the file
                web.Files.Add(DocLib.RootFolder + "/MyDoc.doc", FileContent, true);
 
                /*** If you want to add inside a folder: say "Sales" *******/
                // Get the folder called "Sales"
                SPFolder SubFolder = DocLib.RootFolder.SubFolders["Sales"];
                //Add the file to the sub-folder
                SPFile file = SubFolder.Files.Add(SubFolder.Url + "/MyFile.doc", FileContent, true);
                SubFolder.Update();
 
                //IF you want to Update the Meta data column say "Country"
                SPListItem item = DocLib.Items[file.UniqueId];
                item["Country"] = "Denmark";
                item.Update();
                // OR We can use the Hash Table
                var Metadata = new Hashtable { { "Country""India" } };
                // Add the file
                web.Files.Add(DocLib.RootFolder + "/MyDoc2.doc", FileContent, Metadata, true);
 
                /**** Check-in the file, If the Library has mandatory Columns or Explicit Check-out Enabled *******/
                if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                {
                    file.CheckIn("File uploaded Programmatically !");
                }
 
                /**** Publish the file using File.publish() method If Minor versions enabled! ****/
                //file.Publish("File published Programmatically !");
 
              }
            }
 
        }
    }
}


Read more: http://www.sharepointdiary.com/2012/04/how-to-programmatically-upload-file-to-sharepoint-library.html#ixzz3rrRPk8wh

No comments:

Post a Comment