Downloading Notes Attachments using Paging

This article is about downloading Notes attachment from Dyanmics 365. If you have large number of records from where you want to download attachment, you can face different issues like timeout, slow downloading etc. Here I am going to provide sample code which you can use to download attachments from small set of data.

To download attachment from Dynamics we can query notes entity. We can control data retrieval based on the query, but still sometime our source dataset is more then 5000 so we need to use paging cookie in our retrievemultiple query. While query our entity data if we have used paging cookie feature, the result contains a value for the paging cookie which we can use to fetch next pages.

But while even fetching default 5000 records depending on the notes attachment size it can talk lot of time to query. Recently while working similar requirement, I faced issue while fetching records and so I used following code to fetch small number of records using paging.

 public void DownloadNotesAttachments(QueryExpression query) {
  //number of records you want to query
  int queryCount = 250;
  // Initialize the page number.
  int pageNumber = 1;
  // Initialize the number of records.
  int recordCount = 0;

  // Assign the pageinfo properties.
  query.PageInfo = new PagingInfo();
  query.PageInfo.Count = queryCount;
  query.PageInfo.PageNumber = pageNumber;
  query.PageInfo.PagingCookie = null;

  while (true) {
   EntityCollection notes = service.RetrieveMultiple(query);
   if (notes.Entities != null) {
    foreach(Entity note in notes.Entities) {
     string name = note.GetAttributeValue < string > ("filename");
     string doc_content = note.GetAttributeValue < string > ("documentbody");
     byte[] fileContent = Convert.FromBase64String(doc_content);
     String Location = @ "Folder Path Where you want to download files";
     String filename = note.GetAttributeValue < String > ("filename");
     String noteBody = note.GetAttributeValue < String > ("documentbody");

     string outputFileName = @ "" + Location + "\\" + filename;
     System.IO.File.WriteAllBytes(outputFileName, fileContent);
   // Check for more records, if it returns true.
   if (notes.MoreRecords) {
    query.PageInfo.PagingCookie = notes.PagingCookie;
   } else {
  Console.WriteLine("All files downloaded,Press any key to exit...");


In above code, I am downloading notes attachment based on the query parameter and as I am retrieving small number of records (250) per page so it will start downloading files quickly.

Hope it will help someone!!

Leave a Reply

Your email address will not be published. Required fields are marked *