Download a File from Classic SharePoint

hi below is the code to download file from classic SharePoint list

What the Code Does

  1. Configuration Setup
  • Defines Azure AD app details: tenantId, clientId, thumbprint.
  • Specifies SharePoint site URL, list name, item ID, and local download folder.
  1. Folder Validation
  • Checks if the download folder exists; creates it if not.
  1. Certificate Loading
  • Opens the CurrentUser\My certificate store.
  • Finds the certificate by thumbprint.
  • Throws an exception if the certificate is not found.
  1. Authentication with MSAL
  • Builds a ConfidentialClientApplication using:
    • clientId
    • tenantId
    • Loaded certificate
  • Acquires an access token for SharePoint Online using the .default scope.
  1. SharePoint CSOM Context
  • Creates a ClientContext for the SharePoint site.
  • Adds the Authorization: Bearer {token} header to all requests.
  1. Fetch List Item & Attachments
  • Loads the list item by itemId from the specified list.
  • Loads its AttachmentFiles collection.
  1. Download Attachments
  • Iterates through each attachment.
  • Gets the file by ServerRelativeUrl.
  • Opens a binary stream and saves the file locally in the download folder.
  1. Error Handling
  • Wraps everything in a Try...Catch block to handle exceptions gracefully.

below is the code

Try
’ — Azure AD App & Site Details —
Dim tenantId As String = “”
Dim clientId As String = “”
Dim siteUrl As String = “ ”
Dim thumbprint As String = “”
Dim listName As String = “Sales”
Dim itemId As Integer = 4
Dim downloadFolder As String = “Path”

' --- Ensure download folder exists ---
If Not System.IO.Directory.Exists(downloadFolder) Then
    System.IO.Directory.CreateDirectory(downloadFolder)
End If

' --- Load Certificate ---
Dim cert As System.Security.Cryptography.X509Certificates.X509Certificate2
Using store As New System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser)
    store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly)
    Dim certs As System.Security.Cryptography.X509Certificates.X509Certificate2Collection = store.Certificates.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint, thumbprint, False)
    If certs.Count = 0 Then Throw New Exception($"Certificate with thumbprint {thumbprint} not found.")
    cert = certs(0)
End Using

' --- Build Confidential Client (MSAL) ---
Dim app = Microsoft.Identity.Client.ConfidentialClientApplicationBuilder.Create(clientId) _
            .WithTenantId(tenantId) _
            .WithCertificate(cert) _
            .Build()

' --- Correct scope for SharePoint Online ---
Dim scopes As String() = {"https://schneiderelectric.sharepoint.com/.default"}
Dim authResult = app.AcquireTokenForClient(scopes).ExecuteAsync().Result
Dim accessToken As String = authResult.AccessToken

System.Windows.MessageBox.Show(accessToken)

' --- SharePoint CSOM Context ---
Using ctx As New Microsoft.SharePoint.Client.ClientContext(siteUrl)
    AddHandler ctx.ExecutingWebRequest,
        Sub(sender, e)
            e.WebRequestExecutor.WebRequest.Headers.Add("Authorization", "Bearer " & accessToken)
        End Sub

    ' --- Get list item and attachments ---
    Dim list As Microsoft.SharePoint.Client.List = ctx.Web.Lists.GetByTitle(listName)
    Dim listItem As Microsoft.SharePoint.Client.ListItem = list.GetItemById(itemId)
    ctx.Load(listItem)
    ctx.Load(listItem.AttachmentFiles)
    ctx.ExecuteQuery()

    ' --- Download attachments ---
    If listItem.AttachmentFiles.Count = 0 Then
        Console.WriteLine("No attachments found.")
    Else
        For Each att As Microsoft.SharePoint.Client.Attachment In listItem.AttachmentFiles
            Dim filePath As String = System.IO.Path.Combine(downloadFolder, att.FileName)

            ' Get the file via ServerRelativeUrl
            Dim file As Microsoft.SharePoint.Client.File = ctx.Web.GetFileByServerRelativeUrl(att.ServerRelativeUrl)
            ctx.Load(file)
            ctx.ExecuteQuery()

            ' Open binary stream from File object
            Dim data As Microsoft.SharePoint.Client.ClientResult(Of Stream) = file.OpenBinaryStream()
            ctx.ExecuteQuery()

            ' Save locally
            Using fs As New FileStream(filePath, FileMode.Create)
                data.Value.CopyTo(fs)
            End Using

            Console.WriteLine("Downloaded: " & att.FileName)
        Next
    End If
End Using

Catch ex As Exception
Console.WriteLine("Error: " & ex.Message)
End Try

Check these .xaml and text file where code is shared. Let me know if it works.
SharePointDownload.xaml (1.4 KB)
DownloadFileFromClassicSharepoint.txt (2.5 KB)

From the text file, copy the code and paste in invoke code activity and map the arguments.