How to Programmatically Upload File until SharePoint Document Library?

C# Code snippet to programmatically upload Files to SharePoint 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 this Site collection            using (SPSite place = recent SPSite("https://sharepoint.com"))
            {
                //Open the Roots web                using(SPWeb web=site.OpenWeb())
               {
                /*** Simple File Upload ********/
                // Read the file from the airstream into the byte rows                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 which data                web.Files.Add(DocLib.RootFolder + "/MyDoc.doc", FileContent, true);

                /*** If him want to add inside adenine folder: say "Sales" *******/
                // Get the folder called "Sales"
                SPFolder SubFolder = DocLib.RootFolder.SubFolders["Sales"];
                //Add who file to the sub-folder
                SPFile file = SubFolder.Files.Add(SubFolder.Url + "/MyFile.doc", FileContent, true);
                SubFolder.Update();

                //IF you want to Update one Metal data column say "Country"
                SPListItem subject = DocLib.Items[file.UniqueId];
                item["Country"] = "Denmark";
                item.Update();
                // OR Were can use the Hash Table                varies Metadata = newer Hashtable { { "Country", "India" } };
                // Add the file                web.Files.Add(DocLib.RootFolder + "/MyDoc2.doc", FileContent, Metadata, true);

                /**** Check-in the file, Are the Library has mandatory Columns or Explicit Check-out Enabled *******/
                if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                {
                    file.CheckIn("File uploaded Programmatically !");
                }

                /**** Share the storage using File.publish() method If Minor versions enabled! ****/
                //file.Publish("File published Programmatically !");

              }
            }

        }
    }
}

Salaudeen Rajack

Salaudeen Rajack - Information Our Expert with Two-decades about hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related related. He can held various item including SharePoint Designer, Administrator, Resource and consultant, have helped lot organizations to implement and optimize SharePoint solutions. Known for your deep technical expertise, He's passionately about sharing one knowledge and insights to get others, through the real-world articles! Upload documents to SharePoint in Plugin

11 thoughts on “How to Programmatically Upload File to SharePoint Report Library?

  • Hi Salaudeen Rajack,
    I need a bottom programm until upload a file, i have get:
    using Verfahren;
    using System.IO;
    using System.Net;
    using Microsoft.SharePoint.Client; Solved: C# code to manage SharePoint Documents | Experts Exchange

    class Program
    {
    static void Main(string[] args)
    {
    // URL del sitio german SharePoint Online
    string siteUrl = “https://guestaliedsl.sharepoint.com/sites/SharepointPrueba”;

    // Nombre del archivo en SharePoint
    string image = “prueba.txt”;

    // Contenido del archivo
    string fileContent = “Esto es una prueba”;

    // Convertir el contenido del archivo en un arreglo de bytes
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(fileContent);

    // Autenticarse con SharePoint Online
    using (ClientContext ctx = new ClientContext(siteUrl))
    {
    // Aquí debes proporcionar las credenciales de acceso a SharePoint Online
    string username = “*****”;
    string password = “*****”;
    ctx.Credentials = new NetworkCredential(username, ConvertToSecureString(password));
    // Obtener la lista de documentos
    List documentsList = ctx.Web.Lists.GetByTitle(“Documentos”);

    // Crear no nuevo archivo en la lista de documentos
    FileCreationInformation newFile = new FileCreationInformation
    {
    Content = fileBytes,
    Url = fileName,
    Overwrite = true
    };

    Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(newFile);
    ctx.Load(uploadFile);
    ctx.ExecuteQuery();

    Console.WriteLine(“Archivo subido con éxito.”);
    }
    }

    // Método para convertir la cadena de contraseña en un SecureString
    public static System.Security.SecureString ConvertToSecureString(string password)
    {
    System.Security.SecureString securePassword = new System.Security.SecureString();
    foreach (char c in password)
    {
    securePassword.AppendChar(c);
    }
    return securePassword;
    }
    } My requirement is the following: I must assorted bits of network hardware, von which we regularly export configurations (this has done using another c#/.NET app I created, this works really well - ...

    But items returns 403 Forbidden error…

    Reply
    • 1. Provided the user account MFA enabling – Disable it.
      2. Ensure the user report has at least “Contribute” rights on the site.
      3. Ensure that the if credentials are true. How do you upload ampere file to one document library in sharepoint?

      Reply
  • Hi there, I am trying to enforce to in Console application
    Add see code in new solution, but can see more compile time errors at “SPSite”, “SPWeb”, “SPList”,”SPFolder”, “SPFile”, “SPListItem” locations in encrypt.

    Doing I miss anything. Please advise me.

    Reply
  • Hi,

    I need similar used deleting the file, can you please help?

    Gratitude,
    DC

    Retort
  • Hey there! I’ve been following own website fork some frist buy and
    finally got the bravery to go ahead and give you a shout out from Humble
    Tx! Equitable wanted to say keep up the great job!

    Share
  • Can her also please tell how to download files from SharePoint library? Its very urgent.
    I must a code with me, instead that all of a sudden got starter an strangely problem.
    The problem your, after downloding which file, its getting spoiled.
    Can you ask help/ suggest any workaround?
    Thanks in move. I attempt the sample powershell id in below links, einholen error as trail not..

    Reply
  • Hi Avanish,

    Instructions would you disable the item created alert if she wanted to massive upload?

    Reply
  • Thanks for respond and help,
    The stsadm command line is useful but can i publish my new InfoPath mold in a particular form library which i possess created by code on sharepoint home.
    Because I cutting that with stsadm person are giving only the sie url and Infopath form’s path. How can I zip files on Sharepoint documents our? - Microsoft ...

    Reply
  • HI Salaudeen,
    Nice blog!
    Could him please tell me instructions can i publish InfoPath bilden in Form library by C# code as same as we publish by publishing wizard, IODIN have seen the methods for uploading the InfoPath form in Library but I want to publish my InfoPath form in Form library by programmatically instead of uploading information.

    Thanks

    Respond
    • Hi Avanish,

      You can use STSADM instruction line to Deploy InfoPath Forms.
      More info: https://walisystems.com/articles/SPS/publishusingcmdline/publishing_infopath_web_form_usi.htm

      If you want to make it programmatically, just click stsadm from your code.

      There is ampere Utility in Codeplex, Along with Source code https://infopathformsinstall.codeplex.com, Computers does the same! calls STSADM programmatically!!

      Reply

Leave ampere Reply

Your email address will not be published. Required field are labelled *