ArcGIS Pro 3.8 API Reference Guide
ArcGIS.Core.Data Namespace / RowCursor Class / MoveNext Method
Example

In This Topic
    MoveNext Method (RowCursor)
    In This Topic
    Advances to the next Row in this RowCursor. This method must be called on the MCT. Use QueuedTask.Run.
    Syntax
    public bool MoveNext()
    Public Function MoveNext() As Boolean

    Return Value

    true if the cursor has successfully advanced to the next row; false if the cursor has passed the end of the collection.
    Exceptions
    ExceptionDescription
    A geodatabase-related exception has occurred.
    Remarks
    The RowCursor can only advance sequentially forward. To move the cursor back to the beginning, you will have to reexecute the search to obtain a new row cursor. If MoveNext() returns true, a Row object is created. Even if this row (Current) is not otherwise needed, it should be properly disposed through a call to System.IDisposable.Dispose or with the use of a using statement.
    Example
    Opening a CAD Datastore
    {
      await QueuedTask.Run(() =>
      {
        FileSystemConnectionPath fileConnection = new FileSystemConnectionPath(new Uri("path\\to\\folder\\containing\\CAD"), FileSystemDatastoreType.Cad);
        using (FileSystemDatastore cadDatastore = new FileSystemDatastore(fileConnection))
        {
          //Note: Extension is required
          FeatureClass cadDataset = cadDatastore.OpenDataset<FeatureClass>("hatchplayboundaries.dwg");
    
          // Take note of the pattern for referencing a feature class.
          FeatureClass cadfeatureClass = cadDatastore.OpenDataset<FeatureClass>("hatchplayboundaries.dwg:Polyline");
    
          int numRows = 0;
          using (RowCursor cursor = cadfeatureClass.Search())
          {
            while (cursor.MoveNext())
            {
              numRows++;
            }
          }
        }
      });
    }
    Searching a Table using QueryFilter
    {
      await QueuedTask.Run(() =>
      {
        try
        {
          using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
          using (Table table = geodatabase.OpenDataset<Table>("EmployeeInfo"))
          {
            QueryFilter queryFilter = new QueryFilter
            {
              WhereClause = "COSTCTRN = 'Information Technology'",
              SubFields = "KNOWNAS, OFFICE, LOCATION",
              PostfixClause = "ORDER BY OFFICE"
            };
    
            using (RowCursor rowCursor = table.Search(queryFilter, false))
            {
              while (rowCursor.MoveNext())
              {
                using (Row row = rowCursor.Current)
                {
                  string location = Convert.ToString(row["LOCATION"]);
                  string knownAs = Convert.ToString(row["KNOWNAS"]);
                }
              }
            }
          }
        }
        catch (GeodatabaseFieldException fieldException)
        {
          // One of the fields in the where clause might not exist. There are multiple ways this can be handled:
          // Handle error appropriately
        }
      });
    }
    Searching a FeatureClass using SpatialQueryFilter
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (FeatureClass schoolBoundaryFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.SchoolBoundary"))
        {
          // Using a spatial query filter to find all features which have a certain district name and lying within a given Polygon.
          SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter
          {
            WhereClause = "DISTRCTNAME = 'Indian Prairie School District 204'",
            FilterGeometry = new PolygonBuilderEx(new List<Coordinate2D>
            {
              new Coordinate2D(1021880, 1867396),
              new Coordinate2D(1028223, 1870705),
              new Coordinate2D(1031165, 1866844),
              new Coordinate2D(1025373, 1860501),
              new Coordinate2D(1021788, 1863810)
            }).ToGeometry(),
    
            SpatialRelationship = SpatialRelationship.Within
          };
    
          using (RowCursor indianPrairieCursor = schoolBoundaryFeatureClass.Search(spatialQueryFilter, false))
          {
            while (indianPrairieCursor.MoveNext())
            {
              using (Feature feature = (Feature)indianPrairieCursor.Current)
              {
                // Process the feature. For example...
                Console.WriteLine(feature.GetObjectID());
              }
            }
          }
        }
      });
    }
    Evaluating a QueryDef on a single table
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        {
          QueryDef adaCompilantParksQueryDef = new QueryDef
          {
            Tables = "Park",
            WhereClause = "ADACOMPLY = 'Yes'",
          };
    
          using (RowCursor rowCursor = geodatabase.Evaluate(adaCompilantParksQueryDef, false))
          {
            while (rowCursor.MoveNext())
            {
              using (Row row = rowCursor.Current)
              {
                Feature feature = row as Feature;
                Geometry shape = feature.GetShape();
    
                String type = Convert.ToString(row["ADACOMPLY"]); // will be "Yes" for each row.
    
                try
                {
                  Table table = row.GetTable(); // Will always throw exception.
                }
                catch (NotSupportedException exception)
                {
                  // Handle not supported exception.
                }
              }
            }
          }
        }
      });
    }
    Evaluating a QueryDef on a Join using WHERE Clause
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        {
          QueryDef municipalEmergencyFacilitiesQueryDef = new QueryDef
          {
            SubFields = "EmergencyFacility.OBJECTID, EmergencyFacility.Shape, EmergencyFacility.FACILITYID, FacilitySite.FACILITYID, FacilitySite.FCODE",
            Tables = "EmergencyFacility, FacilitySite",
            WhereClause = "EmergencyFacility.FACNAME = FacilitySite.NAME AND EmergencyFacility.JURISDICT = 'Municipal'",
          };
    
          using (RowCursor rowCursor = geodatabase.Evaluate(municipalEmergencyFacilitiesQueryDef, false))
          {
            while (rowCursor.MoveNext())
            {
              using (Row row = rowCursor.Current)
              {
                Feature feature = row as Feature;
                Geometry shape = feature.GetShape();
    
                long objectID = Convert.ToInt64(row["EmergencyFacility.OBJECTID"]);
                String featureCode = Convert.ToString(row["FacilitySite.FCODE"]);
    
                IReadOnlyList<Field>
                  fields = feature.GetFields(); //Contains one ArcGIS.Core.Data.Field objects for every subfield
              }
            }
          }
        }
      });
    }
    Evaluating a QueryDef on a OUTER JOIN
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        {
          QueryDef queryDefWithLeftOuterJoin = new QueryDef
          {
            Tables = "CommunityAddress LEFT OUTER JOIN MunicipalBoundary on CommunityAddress.Municipality = MunicipalBoundary.Name",
            SubFields = "CommunityAddress.OBJECTID, CommunityAddress.Shape, CommunityAddress.SITEADDID, CommunityAddress.ADDRNUM, CommunityAddress.FULLNAME, CommunityAddress.FULLADDR, CommunityAddress.MUNICIPALITY, MunicipalBoundary.Name, MunicipalBoundary.MUNITYP, MunicipalBoundary.LOCALFIPS",
          };
    
          using (RowCursor rowCursor = geodatabase.Evaluate(queryDefWithLeftOuterJoin, false))
          {
            while (rowCursor.MoveNext())
            {
              using (Row row = rowCursor.Current)
              {
                Feature feature = row as Feature;
                Geometry shape = feature.GetShape();
    
                int siteAddressId = Convert.ToInt32(row["CommunityAddress.SITEADDID"]);
                String stateName = Convert.ToString(row["MunicipalBoundary.name"]);
              }
            }
          }
        }
      });
    }
    Evaluating a QueryDef on a INNER join
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        {
          QueryDef queryDef = new QueryDef()
          {
            Tables = "People INNER JOIN States ON People.FK_STATE_ID = States.OBJECTID",
            SubFields = "People.OBJECTID, People.First_Name, People.Last_Name, People.City, States.State_Name"
          };
    
          using (RowCursor cursor = geodatabase.Evaluate(queryDef))
          {
            while (cursor.MoveNext())
            {
              using (Row row = cursor.Current)
              {
                // Handle row
              }
            }
          }
        }
      });
    }
    Evaluating a QueryDef on a nested - INNER and OUTER join
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        {
          QueryDef queryDef = new QueryDef()
          {
            Tables = "((People INNER JOIN States ON People.FK_STATE_ID = States.OBJECTID) LEFT OUTER JOIN Homes ON People.OBJECTID = Homes.FK_People_ID)",
            SubFields = "People.OBJECTID, People.First_Name, People.Last_Name, States.State_Name, Homes.Address"
          };
    
          using (RowCursor cursor = geodatabase.Evaluate(queryDef, false))
          {
            while (cursor.MoveNext())
            {
              using (Row row = cursor.Current)
              {
                // Handle row
              }
            }
          }
        }
      });
    }
    Joining two tables from different geodatabases
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase sourceGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("Path \\ to \\Geodatabase \\ one"))))
        using (Geodatabase destinationGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("Path \\ to \\Geodatabase \\ two"))))
        using (Table sourceTable = sourceGeodatabase.OpenDataset<Table>("State"))
        using (Table destinationTable = destinationGeodatabase.OpenDataset<Table>("Cities"))
        {
          Field primaryKeyField = sourceTable.GetDefinition().GetFields()
            .FirstOrDefault(field => field.Name.Equals("State.State_Abbreviation"));
          Field foreignKeyField = destinationTable.GetDefinition().GetFields()
            .FirstOrDefault(field => field.Name.Equals("Cities.State"));
    
          VirtualRelationshipClassDescription virtualRelationshipClassDescription = new VirtualRelationshipClassDescription(primaryKeyField, foreignKeyField,
              RelationshipCardinality.OneToMany);
    
          using (RelationshipClass relationshipClass = sourceTable.RelateTo(destinationTable, virtualRelationshipClassDescription))
          {
            JoinDescription joinDescription = new JoinDescription(relationshipClass)
            {
              JoinDirection = JoinDirection.Forward,
              JoinType = JoinType.InnerJoin,
              TargetFields = sourceTable.GetDefinition().GetFields()
            };
    
            using (Join join = new Join(joinDescription))
            {
              Table joinedTable = join.GetJoinedTable();
    
              //Process the joined table. For example ..
              using (RowCursor cursor = joinedTable.Search())
              {
                while (cursor.MoveNext())
                {
                  using (Row row = cursor.Current)
                  {
                    // Use Row
                  }
                }
              }
            }
          }
        }
      });
    }
    Pagination in QueryFilter
    {
      Task QueryFilterWithPaginationAsync(Table table, List<long> objectIDs) => QueuedTask.Run(() =>
      {
        int rowsPerBatch = 100;
        int offset = 0;
    
        // Query filter
        // Some datastores support pagination only through an SQL postfix clause
        QueryFilter queryFilter = new QueryFilter()
        {
          ObjectIDs = objectIDs,
          PostfixClause = "ORDER BY OBJECTID"
        };
    
        // Fetch rows in a batch from a table
        for (int index = offset; index <= objectIDs.Count; index += rowsPerBatch)
        {
          // Set number of rows to return from a table
          queryFilter.RowCount = rowsPerBatch;
    
          // Set positional offset to skip number of rows from a table
          queryFilter.Offset = index;
    
          using (RowCursor cursor = table.Search(queryFilter))
          {
            while (cursor.MoveNext())
            {
              using (Row row = cursor.Current)
              {
                Console.WriteLine(row.GetObjectID());
              }
            }
          }
        }
      });
    }
    Illustrate version conflict information from a reconcile operation
    {
      Task GetVersionConflictsInfoInUpdateDeleteTypeAsync(
        ServiceConnectionProperties featureServiceConnectionProperties,
        string featureClassName) => QueuedTask.Run(() =>
      {
        // To illustrate the conflict between versions,
        // the feature is updated in the child version and deleted in the parent version.
    
        long featureObjectIDForEdit = Int64.MinValue;
    
        // Get branch versioned service
        using (Geodatabase fsGeodatabase = new Geodatabase(featureServiceConnectionProperties))
        using (VersionManager versionManager = fsGeodatabase.GetVersionManager())
        using (Version defaultVersion = versionManager.GetDefaultVersion())
        using (Geodatabase defaultGeodatabase = defaultVersion.Connect())
        using (FeatureClass defaultFeatureClass = defaultGeodatabase.OpenDataset<FeatureClass>(featureClassName))
        using (FeatureClassDefinition defaultFeatureClassDefinition = defaultFeatureClass.GetDefinition())
        {
          // Create a feature in the default version to edit in a branch
          defaultGeodatabase.ApplyEdits(() =>
          {
            using (RowBuffer rowBuffer = defaultFeatureClass.CreateRowBuffer())
            {
              rowBuffer["NAME"] = "Loblolly Pine";
              rowBuffer["TREEAGE"] = 1;
              rowBuffer[defaultFeatureClassDefinition.GetShapeField()] = new MapPointBuilderEx(new Coordinate2D(1, 1),
                SpatialReferenceBuilder.CreateSpatialReference(4152, 0)).ToGeometry();
    
              using (Feature feature = defaultFeatureClass.CreateRow(rowBuffer))
              {
                featureObjectIDForEdit = feature.GetObjectID();
              }
            }
          });
          // Add newly created feature in the filter
          QueryFilter queryFilter = new QueryFilter { ObjectIDs = new List<long> { featureObjectIDForEdit } };
    
          // Create a branch version
          VersionDescription versionDescription = new VersionDescription("UpdateDeleteConflictType",
            "Update-Delete version conflict type", VersionAccessType.Public);
    
          // Edit the feature in the branch
          using (Version editVersion = versionManager.CreateVersion(versionDescription))
          using (Geodatabase branchGeodatabase = editVersion.Connect())
          using (FeatureClass featureClass = branchGeodatabase.OpenDataset<FeatureClass>(featureClassName))
          using (RowCursor rowCursor = featureClass.Search(queryFilter, false))
          {
            branchGeodatabase.ApplyEdits(() =>
            {
              while (rowCursor.MoveNext())
              {
                using (Row row = rowCursor.Current)
                {
                  row["TREEAGE"] = 100;
                  row["NAME"] = $"{row["Name"]}_EditInBranch";
                  row.Store();
                }
              }
            });
    
            // Delete the feature from the default version
            defaultGeodatabase.ApplyEdits(() =>
            {
              defaultFeatureClass.DeleteRows(queryFilter);
            });
    
            // Reconcile options
            ReconcileOptions reconcileOptions = new ReconcileOptions(defaultVersion)
            {
              ConflictResolutionType = ConflictResolutionType.FavorEditVersion,
              ConflictDetectionType = ConflictDetectionType.ByRow,
              ConflictResolutionMethod = ConflictResolutionMethod.Continue
            };
    
            // Reconcile with default
            ReconcileResult reconcileResult = editVersion.Reconcile(reconcileOptions);
    
            // Check for conflicts
            bool hasConflictsReconcileResults = reconcileResult.HasConflicts;
            bool hasConflictsAfterReconcile = editVersion.HasConflicts();
    
            // Fetch conflicts
            IReadOnlyList<Conflict> conflictsAfterReconcile = editVersion.GetConflicts();
    
            // Iterate conflicts
            foreach (Conflict conflict in conflictsAfterReconcile)
            {
              // Object ID of row where conflict occurs
              long objectId = conflict.ObjectID;
    
              ConflictType conflictType = conflict.ConflictType;
    
              IReadOnlyList<FieldValue> ancestorVersionValues = conflict.AncestorVersionValues;
              object nameAncestor = ancestorVersionValues.FirstOrDefault(f => f.FieldName.Contains("NAME")).Value;
              object treeAgeAncestor =
                ancestorVersionValues.FirstOrDefault(f => f.FieldName.Contains("TREEAGE")).Value;
    
              IReadOnlyList<FieldValue> childVersionValues = conflict.ChildVersionValues;
              object nameChild = childVersionValues.FirstOrDefault(f => f.FieldName.Contains("NAME")).Value;
              object treeAgeChild = childVersionValues.FirstOrDefault(f => f.FieldName.Contains("TREEAGE")).Value;
    
              IReadOnlyList<FieldValue> parentVersionValues = conflict.ParentVersionValues;
    
              IReadOnlyList<Field> originalFields = defaultFeatureClassDefinition.GetFields();
    
              string datasetName = conflict.DatasetName;
            }
          }
        }
      });
    }
    Modifying a Row
    {
      await QueuedTask.Run(() =>
      {
        string message = String.Empty;
        bool modificationResult = false;
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
        {
          EditOperation editOperation = new EditOperation();
          editOperation.Callback(context =>
          {
            QueryFilter openCutFilter = new QueryFilter { WhereClause = "ACTION = 'Open Cut'" };
    
            using (RowCursor rowCursor = enterpriseTable.Search(openCutFilter, false))
            {
              TableDefinition tableDefinition = enterpriseTable.GetDefinition();
              int subtypeFieldIndex = tableDefinition.FindField(tableDefinition.GetSubtypeField());
    
              while (rowCursor.MoveNext())
              {
                using (Row row = rowCursor.Current)
                {
                  // In order to update the Map and/or the attribute table.
                  // Has to be called before any changes are made to the row.
                  context.Invalidate(row);
    
                  row["ASSETNA"] = "wMainOpenCut";
    
                  if (Convert.ToDouble(row["COST"]) > 700)
                  {
                    // Abandon asset if cost is higher than 700 (if that is what you want to do).
                    row["ACTION"] = "Open Cut Abandon";
                    row[subtypeFieldIndex] = 3; //subtype value for "Abandon"
                  }
    
                  //After all the changes are done, persist it.
                  row.Store();
    
                  // Has to be called after the store too.
                  context.Invalidate(row);
                }
              }
            }
          }, enterpriseTable);
    
          try
          {
            modificationResult = editOperation.Execute();
            if (!modificationResult)
            {
              message = editOperation.ErrorMessage;
            }
          }
          catch (GeodatabaseException exObj)
          {
            message = exObj.Message;
          }
        }
    
        if (!string.IsNullOrEmpty(message))
        {
          Debug.WriteLine(message);
        }
      });
    }
    Modifying a Feature
    {
      await QueuedTask.Run(() =>
      {
        string message = String.Empty;
        bool modificationResult = false;
    
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite"))
        {
          FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();
    
          int ownTypeIndex = facilitySiteDefinition.FindField("OWNTYPE");
          int areaIndex = facilitySiteDefinition.FindField(facilitySiteDefinition.GetAreaField());
    
          EditOperation editOperation = new EditOperation();
          editOperation.Callback(context =>
          {
            QueryFilter queryFilter = new QueryFilter
            {
              WhereClause = "FCODE = 'Hazardous Materials Facility' AND OWNTYPE = ' '"
            };
    
            using (RowCursor rowCursor = enterpriseFeatureClass.Search(queryFilter, false))
            {
              while (rowCursor.MoveNext())
              {
                using (Feature feature = (Feature)rowCursor.Current)
                {
                  // In order to update the Map and/or the attribute table.
                  // Has to be called before any changes are made to the row
                  context.Invalidate(feature);
    
                  // Transfer all Hazardous Material Facilities to the City.
                  feature[ownTypeIndex] = "Municipal";
    
                  if (Convert.ToDouble(feature[areaIndex]) > 50000)
                  {
                    // Set the Shape of the feature to whatever you need.
                    List<Coordinate2D> newCoordinates = new List<Coordinate2D>
                    {
                        new Coordinate2D(1021570, 1880583),
                        new Coordinate2D(1028730, 1880994),
                        new Coordinate2D(1029718, 1875644),
                        new Coordinate2D(1021405, 1875397)
                    };
    
                    feature.SetShape(new PolygonBuilderEx(newCoordinates).ToGeometry());
                  }
    
                  feature.Store();
    
                  // Has to be called after the store too
                  context.Invalidate(feature);
                }
              }
            }
          }, enterpriseFeatureClass);
    
          try
          {
            modificationResult = editOperation.Execute();
            if (!modificationResult)
            {
              message = editOperation.ErrorMessage;
            }
          }
          catch (GeodatabaseException exObj)
          {
            message = exObj.Message;
          }
        }
    
        if (!string.IsNullOrEmpty(message))
        {
          Debug.WriteLine(message);
        }
      });
    }
    Deleting a Row/Feature
    {
      await QueuedTask.Run(() =>
      {
        string message = String.Empty;
        bool deletionResult = false;
    
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
        {
          EditOperation editOperation = new EditOperation();
          editOperation.Callback(context =>
          {
            QueryFilter openCutFilter = new QueryFilter { WhereClause = "ACTION = 'Open Cut'" };
    
            using (RowCursor rowCursor = enterpriseTable.Search(openCutFilter, false))
            {
              while (rowCursor.MoveNext())
              {
                using (Row row = rowCursor.Current)
                {
                  // In order to update the Map and/or the attribute table. Has to be called before the delete.
                  context.Invalidate(row);
    
                  row.Delete();
                }
              }
            }
          }, enterpriseTable);
    
          try
          {
            deletionResult = editOperation.Execute();
            if (!deletionResult)
            {
              message = editOperation.ErrorMessage;
            }
          }
          catch (GeodatabaseException exObj)
          {
            message = exObj.Message;
          }
        }
    
        if (!string.IsNullOrEmpty(message))
        {
          Debug.WriteLine(message);
        }
      });
    }
    Split a feature by geometry
    {
      Task SplitALineByPointAsync(FeatureClass lineFeatureClass, MapPoint xPoint) => QueuedTask.Run(() =>
      {
        using (RowCursor rowCursor =
               lineFeatureClass.Search(new QueryFilter() { ObjectIDs = new List<long>() { 1 } }))
        {
          if (rowCursor.MoveNext())
          {
            using (Feature feature = rowCursor.Current as Feature)
            {
              // ObjectIDs of newly created lines
              IReadOnlyList<long> splits = feature.Split(xPoint);
            }
          }
        }
      });
    }
    Adding Attachments
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (FeatureClass parkFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.Park"))
        {
          QueryFilter filter = new QueryFilter { WhereClause = "NUMPARKING > 0" };
    
          using (RowCursor parkingCursor = parkFeatureClass.Search(filter, false))
          {
            while (parkingCursor.MoveNext())
            {
              using (MemoryStream stream = CreateMemoryStreamFromContentsOf("Sample.xml"))
              {
                Attachment attachment = new Attachment("Sample.xml", "text/xml", stream);
    
                using (Row row = parkingCursor.Current)
                {
                  long attachmentId = row.AddAttachment(attachment);
                }
              }
            }
          }
        }
      });
      // Helper method to read a file into a memory stream
      MemoryStream CreateMemoryStreamFromContentsOf(String fileNameWithPath)
      {
        MemoryStream memoryStream = new MemoryStream();
    
        using (FileStream file = new FileStream(fileNameWithPath, FileMode.Open, FileAccess.Read))
        {
          byte[] bytes = new byte[file.Length];
          file.Read(bytes, 0, (int)file.Length);
          memoryStream.Write(bytes, 0, (int)file.Length);
        }
    
        return memoryStream;
      }
    }
    Updating Attachments
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (FeatureClass landUseCaseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.LandUseCase"))
        {
          QueryFilter filter = new QueryFilter { WhereClause = "CASETYPE = 'Rezoning'" };
    
          using (RowCursor landUseCursor = landUseCaseFeatureClass.Search(filter, false))
          {
            while (landUseCursor.MoveNext())
            {
              using (Feature rezoningUseCase = (Feature)landUseCursor.Current)
              {
                IReadOnlyList<Attachment> rezoningAttachments = rezoningUseCase.GetAttachments();
                IEnumerable<Attachment> filteredAttachments = rezoningAttachments.Where(attachment => !attachment.GetName().Contains("rezoning"));
    
                foreach (Attachment attachmentToUpdate in filteredAttachments)
                {
                  attachmentToUpdate.SetName(attachmentToUpdate.GetName().Replace(".pdf", "Rezoning.pdf"));
                  rezoningUseCase.UpdateAttachment(attachmentToUpdate);
                }
              }
            }
          }
        }
      });
    }
    Deleting Attachments
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (Table inspectionTable = geodatabase.OpenDataset<Table>("luCodeInspection"))
        {
          QueryFilter queryFilter = new QueryFilter { WhereClause = "ACTION = '1st Notice'" };
    
          using (RowCursor cursor = inspectionTable.Search(queryFilter, false))
          {
            while (cursor.MoveNext())
            {
              using (Row currentRow = cursor.Current)
              {
                IReadOnlyList<Attachment> rowAttachments = currentRow.GetAttachments(null, true);
                IEnumerable<Attachment> attachments = rowAttachments.Where(attachment =>
                  attachment.GetContentType().Equals("application/pdf"));
    
                IReadOnlyList<long> attachmentIDs =
                  attachments.Select(attachment => attachment.GetAttachmentID()) as IReadOnlyList<long>;
                IReadOnlyDictionary<long, Exception> failures = currentRow.DeleteAttachments(attachmentIDs);
    
                if (failures.Count > 0)
                {
                  //process errors
                }
              }
            }
          }
        }
      });
    }
    Reading a Blob field
    {
      Task ReadBlobFieldAsync(Table table, QueryFilter queryFilter, string blobFieldName) => QueuedTask.Run(() =>
      {
        const string imageFileBaseName = "C:\\path\\to\\image\\directory\\Image";
    
        // For each row that satisfies the search criteria, write the blob field out to an image file
        using (RowCursor rowCursor = table.Search(queryFilter))
        {
          int fileCount = 0;
          while (rowCursor.MoveNext())
          {
            using (Row row = rowCursor.Current)
            {
              // Read the blob field into a MemoryStream
              MemoryStream memoryStream = row[blobFieldName] as MemoryStream;
    
              // Create a file
              using (FileStream outputFile = new FileStream(imageFileBaseName + fileCount.ToString(),
                       FileMode.Create, FileAccess.Write))
              {
                // Write the MemoryStream into the file
                memoryStream.WriteTo(outputFile);
              }
            }
          }
        }
      });
    }
    Getting Rows related by RelationshipClass
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections"))
        using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.luCodeViolation"))
        using (Table inspectionTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.luCodeInspection"))
        {
          List<Row> jeffersonAveViolations = new List<Row>();
          QueryFilter queryFilter = new QueryFilter { WhereClause = "LOCDESC LIKE '%Jefferson%'" };
    
          using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false))
          {
            while (rowCursor.MoveNext())
            {
              jeffersonAveViolations.Add(rowCursor.Current);
            }
          }
    
          IReadOnlyList<Row> relatedOriginRows = null;
          IReadOnlyList<Row> relatedDestinationRows = null;
    
          try
          {
            QueryFilter filter = new QueryFilter { WhereClause = "ACTION = '1st Notice'" };
    
            using (Selection selection = inspectionTable.Select(filter, SelectionType.ObjectID, SelectionOption.Normal))
            {
              relatedOriginRows = relationshipClass.GetRowsRelatedToDestinationRows(selection.GetObjectIDs());
            }
    
            bool containsJeffersonAve = relatedOriginRows.Any(row => Convert.ToString(row["LOCDESC"]).Contains("Jefferson"));
    
            List<long> jeffersonAveViolationObjectIds = jeffersonAveViolations.Select(row => row.GetObjectID()).ToList();
    
            relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(jeffersonAveViolationObjectIds);
            bool hasFirstNoticeInspections = relatedDestinationRows.Any(row => Convert.ToString(row["ACTION"]).Contains("1st Notice"));
          }
          finally
          {
            Dispose(jeffersonAveViolations);
            Dispose(relatedOriginRows);
            Dispose(relatedDestinationRows);
          }
        }
      });
    
      void Dispose(IEnumerable<Row> rows)
      {
        foreach (Row row in rows)
        {
          row.Dispose();
        }
      }
    }
    Deleting a Relationship
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections"))
        using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.luCodeViolation"))
        {
          QueryFilter queryFilter = new QueryFilter { WhereClause = "LOCDESC LIKE '%Jefferson%'" };
    
          using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false))
          {
            if (!rowCursor.MoveNext())
            {
              return;
            }
    
            using (Row jeffersonAveViolation = rowCursor.Current)
            {
              IReadOnlyList<Row> relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(new List<long>
                  { jeffersonAveViolation.GetObjectID() });
    
              try
              {
                EditOperation editOperation = new EditOperation();
                editOperation.Callback(context =>
                {
                  foreach (Row relatedDestinationRow in relatedDestinationRows)
                  {
                    try
                    {
                      relationshipClass.DeleteRelationship(jeffersonAveViolation, relatedDestinationRow);
                    }
                    catch (GeodatabaseRelationshipClassException exception)
                    {
                      Console.WriteLine(exception);
                    }
                  }
                }, relationshipClass);
    
                bool editResult = editOperation.Execute();
              }
              finally
              {
                foreach (Row row in relatedDestinationRows)
                {
                  row.Dispose();
                }
              }
            }
          }
        }
      });
    }
    Creating a row buffer from a template row
    {
      Task CreateRowBufferFromARowAsync(Table table) => QueuedTask.Run(() =>
      {
        using (RowCursor rowCursor = table.Search())
        {
          if (rowCursor.MoveNext())
          {
            using (Row templateRow = rowCursor.Current)
            {
              RowBuffer rowBuffer = table.CreateRowBuffer(templateRow);
    
              // Manipulate row buffer
              // Doesn't allow copying values of ObjectID and GlobalID
              //
              // rowBuffer["Field"] = "Update";
              //
    
              // Create a new row
              table.CreateRow(rowBuffer);
            }
          }
        }
      });
    }
    Spatial query filter with DE9-IM spatial relationships
    {
      Task FindSpatiallyRelatedFeaturesUsingDE9IMPredicateAsync(Geodatabase geodatabase, FeatureClass polygonFeatureClass, FeatureClass polylineFeatureClass) => QueuedTask.Run(() =>
      {
        using (RowCursor polygonRowCursor = polygonFeatureClass.Search(new QueryFilter()))
        {
          if (polygonRowCursor.MoveNext())
          {
            using (Feature polygonFeature = polygonRowCursor.Current as Feature)
            {
              // DE9IM predicate string to find overlapping features
              string overlappingDE9IM = "1*T***T**";
    
              SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter()
              {
                FilterGeometry = polygonFeature.GetShape(),
                SpatialRelationship = SpatialRelationship.Relation,
                SpatialRelationshipDescription = overlappingDE9IM
              };
    
              using (RowCursor overlappingPolyline = polylineFeatureClass.Search(spatialQueryFilter))
              {
                while (overlappingPolyline.MoveNext())
                {
                  // Overlapping polylines on the polygon
                }
              }
            }
          }
        }
      });
    }
    Requirements

    Target Platforms: Windows 11 Home, Pro, Enterprise (64 bit)

    ArcGIS Pro version: 3.0 or higher.
    See Also