How to get unique id of file attachment CSOM SharePoint 2013 OnPremise

ASR 671 Reputation points
2021-09-30T15:07:07.857+00:00

Hi,
I need to get the unique id of the list attachment. For the document library, I am able to get it via "ListItemAllFields" but I guess it can't work that same way for list attachment. Any alternatives are available. I am targeting SharePoint 2013.

SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,742 questions
SharePoint Server Development
SharePoint Server Development
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Development: The process of researching, productizing, and refining new or existing technologies.
1,576 questions
0 comments No comments
{count} votes

Accepted answer
  1. CaseyYang-MSFT 10,321 Reputation points
    2021-10-01T07:13:04.337+00:00

    Hi @ASR ,

    Per my test, we are not able to get unique id of attachment. But we could get the item id by the following PowerShell commands.

    PowerShell Commands:

    $web = Get-SPWeb -Identity http://xxx/sites/xxx  
    $list = $web.Lists["yourlistname"]  
    foreach ($item in $list.Items)  
    {  
    $attachmentCollection = $item.Attachments  
    $folder = $web.GetFolder($attachmentCollection.UrlPrefix);  
    foreach ($file in $folder.Files)  
    {  
    Write-Host $item.Id  
    }  
    }  
    

    If an Answer is helpful, please click "Accept Answer" and upvote it.

    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.


1 additional answer

Sort by: Most helpful
  1. Sharath Kumar Aluri 3,071 Reputation points
    2021-09-30T16:22:39.407+00:00

    I don't think you can get the unique id for the list attachments but you can get item id for the attachments. try with the below code.

    using Microsoft.SharePoint.Client;
    using NLog;
    using System;
    using System.IO;
    using System.Net;
    
    namespace SiteActions.Task
    {
      class Program
      {
      //You can get NLog from NuGet
      //http://www.nuget.org/packages/nlog
      private static Logger logger = LogManager.GetCurrentClassLogger();
    
      static void Main(string[] args)
      {
        try
        {
        int startListID;
        Console.WriteLine("Enter Starting List ID");
        if (!Int32.TryParse(Console.ReadLine(), out startListID))
        {
          Console.WriteLine("Invalid ID");
          Console.WriteLine("Press any key to exit...");
          Console.ReadKey();
          return;
        }
    
        String siteUrl = "http://siteaction.net/sites/teamsite";
        String listName = "SharePoint List Name";
        NetworkCredential credentials =
                    new NetworkCredential("username", "password", "domain");
    
        using (ClientContext clientContext = new ClientContext(siteUrl))
        {
           Console.WriteLine("Started Attachment Download " + siteUrl);
           logger.Info("Started Attachment Download" + siteUrl);
           clientContext.Credentials = credentials;
    
           //Get the Site Collection
           Site oSite = clientContext.Site;
           clientContext.Load(oSite);
           clientContext.ExecuteQuery();
    
           // Get the Web
           Web oWeb = clientContext.Web;
           clientContext.Load(oWeb);
           clientContext.ExecuteQuery();
    
           CamlQuery query = new CamlQuery();
           query.ViewXml = @"";
    
           List oList = clientContext.Web.Lists.GetByTitle(listName);
           clientContext.Load(oList);
           clientContext.ExecuteQuery();
    
           ListItemCollection items = oList.GetItems(query);
           clientContext.Load(items);
           clientContext.ExecuteQuery();
    
           foreach (ListItem listItem in items)
           {
              if (Int32.Parse(listItem["ID"].ToString()) >= startListID ){
    
              Console.WriteLine("Process Attachments for ID " +
                    listItem["ID"].ToString());
    
              Folder folder =
                    oWeb.GetFolderByServerRelativeUrl(oSite.Url +
                    "/Lists/"+listName+/Attachments/" +
                    listItem["ID"]);
    
              clientContext.Load(folder);
    
              try
              {
                 clientContext.ExecuteQuery();
              }
              catch (ServerException ex)
              {
                 logger.Info(ex.Message);
                 Console.WriteLine(ex.Message);
                 logger.Info("No Attachment for ID " + listItem["ID"].ToString());
                 Console.WriteLine("No Attachment for ID " + listItem["ID"].ToString());
              }
    
              FileCollection attachments = folder.Files;
              clientContext.Load(attachments);
              clientContext.ExecuteQuery();
    
              foreach (Microsoft.SharePoint.Client.File oFile in folder.Files)
              {
                 logger.Info("Found Attachment for ID " +
                       listItem["ID"].ToString());
    
                 Console.WriteLine("Found Attachment for ID " +
                       listItem["ID"].ToString());
    
                 FileInfo myFileinfo = new FileInfo(oFile.Name);
                 WebClient client1 = new WebClient();
                 client1.Credentials = credentials;
    
                 logger.Info("Downloading " +
                       oFile.ServerRelativeUrl);
    
                 Console.WriteLine("Downloading " +
                       oFile.ServerRelativeUrl);
    
                 byte[] fileContents =
                       client1.DownloadData("http://siteaction.net" +
                       oFile.ServerRelativeUrl);
    
                 FileStream fStream = new FileStream(@"C:Temp" +
                       oFile.Name, FileMode.Create);
    
                 fStream.Write(fileContents, 0, fileContents.Length);
                 fStream.Close();
              }
            }
          }
        }
        }
        catch (Exception e)
        {
          logger.ErrorException(e.Message, e);
          logger.Error(e.StackTrace);
          Console.WriteLine(e.Message);
          Console.WriteLine(e.StackTrace);
        }
        }
      }
    }
    

    Ref: https://social.technet.microsoft.com/Forums/office/en-US/3881057d-6a43-4f07-8387-23d6a6dd9648/sharepoint-list-items-get-attachments-c-console-app?forum=sharepointgeneral

    Thanks & Regards,
    Sharath Aluri

    0 comments No comments