How to upload a file to SharePoint

Braian Anderson 20 Reputation points
2024-08-21T19:56:02.33+00:00

I'm trying to create a code to upload files to SharePoint. I've already attempted using Microsoft Graph and CSOM, but I haven't been successful. The closest I've gotten is with the code I shared here, but I'm receiving the following error:

'SharePoint Identity Client Runtime Library (IDCRL) did not get a response from the Login server.'

I would greatly appreciate a step-by-step guide on how to upload files and also read them using code. Can anyone help me? Thank you!

using (ClientContext context = new ClientContext(siteUrl))
{ 

  var securePassword = new SecureString();

  foreach (char c in password)
  {
      securePassword.AppendChar(c);
  }

  securePassword.MakeReadOnly();

  context.Credentials = new SharePointOnlineCredentials(email, securePassword);

  Web webContext = context.Web;

  Microsoft.SharePoint.Client.List documentLibrary = webContext.Lists.GetByTitle(driveId);

  FileCreationInformation newFile = new FileCreationInformation
  {
      ContentStream = new FileStream(filePath, FileMode.Open),
      Url = Path.GetFileName(filePath),
      Overwrite = true
  };

  Microsoft.SharePoint.Client.File uploadFile = documentLibrary.RootFolder.Files.Add(newFile);

  context.Load(uploadFile);

  context.ExecuteQuery();

  Console.WriteLine("Success: " + uploadFile.ServerRelativeUrl);

  }
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,800 questions
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
10,631 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
2,901 questions
{count} votes

Accepted answer
  1. Emily Du-MSFT 45,586 Reputation points Microsoft Vendor
    2024-08-22T09:25:37.4166667+00:00

    1.PnP PowerShell

    #Config Variables
    $SiteURL = "https://tenant.sharepoint.com/sites/test"
    $SourceFilePath ="C:\document.docx"
    $DestinationPath = "Shared Documents" #Site Relative Path of the Library
     
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -interactive
          
    #powershell pnp to upload file to sharepoint online
    Add-PnPFile -Path $SourceFilePath -Folder $DestinationPath
    

    2.CSOM

        string userName = "xxx@xxxx.onmicrosoft.com";
        string password = "xxx";
        var securePassword = new SecureString();
        foreach (char c in password)
        {
            securePassword.AppendChar(c);
        }
        using (var clientContext = new ClientContext("https://tenant.sharepoint.com/sites/test"))
        {
            clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);
            Web web = clientContext.Web;
            clientContext.Load(web, a => a.ServerRelativeUrl);
            clientContext.ExecuteQuery();
            List documentsList = clientContext.Web.Lists.GetByTitle("Shared Documents");
    
            var fileCreationInformation = new FileCreationInformation();
            //Assign to content byte[] i.e. documentStream
    
            fileCreationInformation.Content = System.IO.File.ReadAllBytes(@"C:\document.docx");
            //Allow owerwrite of document
    
            fileCreationInformation.Overwrite = true;
            //Upload URL
    
            fileCreationInformation.Url = "https://tenant.sharepoint.com/sites/test/" + "Shared Documents" + "/documents.docx
    ";
    
            Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);
    
            //Update the metadata for a field having name "DocType"
            uploadFile.ListItemAllFields["Title"] = "UploadedviaCSOM";
    
            uploadFile.ListItemAllFields.Update();
            clientContext.ExecuteQuery();
    
        }
    

    3.Graph

    https://medium.com/@mitchelldalehein25/uploading-files-to-sharepoint-using-microsoft-graph-api-c-0edc689fb388

    Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.