ArcGIS Engine开发Geodatabase代码(一)——Cursors

时间:2013-4-25    作者:悬浮的青春    分类:


/**/

  ESRI Developer Summit 2009

 
Developer's Guide to the Geodatabase

  Code Samples

 
6 April 2009

/**/

开发环境:

  • ArcGIS Engine9.3/9mBoundaryZGeovu18uMFXDM9L Content-Disposition: form-data; name="content"/******************************************/
     * ESRI Developer Summit 2009
     * Developer's Guide to the Geodatabase
     * Code Samples
     * 6 April 2009

    /******************************************/

    开发环境:

    • ArcGIS Engine9.3/9.3.1
    • VS2008

    关于版本的接口差别参考:http://help.arcgis.com/en/sdk/10.0/arcobjects_net/conceptualhelp/index.html#/Type_changes_between_9_3_and_10/000100000408000000/

    以上代码主要内容就是对ArcGIS Engine中关于Cursor的使用,特别是Search(查询功能),Insert(增加数据),Update(更新数据)等

    重点关注:区别去普通Store的保存方法,使用featurecursor.UpdateCursor等


    1. using System;  
    2. using System.IO;  
    3. using System.Runtime.InteropServices;  
    4. using ESRI.ArcGIS.ADF;  
    5. using ESRI.ArcGIS.DataSourcesGDB;  
    6. using ESRI.ArcGIS.esriSystem;  
    7. using ESRI.ArcGIS.Geodatabase;  
    8. using ESRI.ArcGIS.Geometry;  
    9.   
    10. namespace CursorDemo  
    11. {  
    12.     public class CursorDemo  
    13.     {  
    14.         public static void Main(string[] args)  
    15.         {  
    16.             #region Licensing  
    17.             // Set up the licencing. NOTE: This sample assumes that you are using ArcInfo Desktop.  
    18.             // You will need to adjust this code if using ArcEngine or ArcEditor.  
    19.             IAoInitialize aoInitialize = new AoInitializeClass();  
    20.             esriLicenseStatus licenseStatus = aoInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcInfo);  
    21.             if (licenseStatus != esriLicenseStatus.esriLicenseCheckedOut)  
    22.             {  
    23.                 Console.WriteLine("Unable to check-out an ArcInfo license, error code is {0}", licenseStatus);  
    24.                 return;  
    25.             }  
    26.             #endregion  
    27.   
    28.             // If test data exists from a previous run, delete it.  
    29.             if (Directory.Exists("CursorDemo.gdb"))  
    30.             {  
    31.                 Directory.Delete("CursorDemo.gdb"true);  
    32.             }  
    33.   
    34.             // Copy the test data from this section's Data directory.  
    35.             Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");  
    36.             IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);  
    37.             IWorkspaceName sourceWorkspaceName = new WorkspaceNameClass  
    38.             {  
    39.                 PathName = @"..\..\..\Data\CursorDemo.gdb",  
    40.                 WorkspaceFactoryProgID = "esriDataSourcesGDB.FileGDBWorkspaceFactory"  
    41.             };  
    42.             IWorkspaceName copiedWorkspaceName = null;  
    43.             workspaceFactory.Copy(sourceWorkspaceName, Environment.CurrentDirectory, out copiedWorkspaceName);  
    44.   
    45.             // Open the copied data.  
    46.             IName copiedName = (IName)copiedWorkspaceName;  
    47.             IWorkspace workspace = (IWorkspace)copiedName.Open();  
    48.             IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;  
    49.   
    50.             // Open the two feature classes used in this demo.  
    51.             IFeatureClass parcelsFeatureClass = featureWorkspace.OpenFeatureClass("Parcels");  
    52.             IFeatureClass pipesFeatureClass = featureWorkspace.OpenFeatureClass("Pipes");  
    53.   
    54.             // The first demo, SearchCursorDemo, will display the Parcel IDs of all residential  
    55.             // parcels within a certain extent.  
    56.             SearchCursorDemo(parcelsFeatureClass);  
    57.   
    58.             // The second demo, UpdateCursorDemo, will change the all parcels zoned as "Manufacturing"  
    59.             // to "Commercial".  
    60.             UpdateCursorDemo(workspace, parcelsFeatureClass);  
    61.   
    62.             // The third demo, InsertCursorDemo, will create one hundred new pipe features using  
    63.             // an insert cursor.  
    64.             InsertCursorDemo(workspace, pipesFeatureClass);  
    65.   
    66.             // Shutdown the licensing.  
    67.             aoInitialize.Shutdown();  
    68.         }  
    69.   
    70.         /// <summary>  
    71.         /// This sample queries a feature class of parcels, finding the Parcel IDs of all residential  
    72.         /// features that are within a given extent.  
    73.         /// </summary>  
    74.         /// <param name="featureClass">The feature class to query.</param>  
    75.         private static void SearchCursorDemo(IFeatureClass featureClass)  
    76.         {  
    77.             // Create an envelope that will define the spatial extent of the query.  
    78.             IEnvelope envelope = new EnvelopeClass();  
    79.             envelope.PutCoords(506000, 684500, 506500, 685000);  
    80.   
    81.             // Create a new spatial filter.  
    82.             ISpatialFilter spatialFilter = new SpatialFilterClass  
    83.             {  
    84.                 Geometry = envelope,  
    85.                 GeometryField = featureClass.ShapeFieldName,  
    86.                 SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects,  
    87.                 SubFields = "Parcel_ID",  
    88.                 WhereClause = "ZONING_S = 'R'"  
    89.             };  
    90.   
    91.             // Find the index of the Parcel_ID field. This is required to display the query results.  
    92.             int parcelIdIndex = featureClass.FindField("Parcel_ID");  
    93.   
    94.             using (ComReleaser comReleaser = new ComReleaser())  
    95.             {  
    96.                 // Query the feature class to get a feature cursor. We can use a recycling  
    97.                 // cursor because we're only going to be reading the data.  
    98.                 IFeatureCursor featureCursor = featureClass.Search(spatialFilter, true);  
    99.                 comReleaser.ManageLifetime(featureCursor);  
    100.   
    101.                 // Iterate through the query results.  
    102.                 IFeature feature = null;  
    103.                 while ((feature = featureCursor.NextFeature()) != null)  
    104.                 {  
    105.                     // Display the current feature's Parcel ID.  
    106.                     Console.WriteLine("Parcel found: {0}", feature.get_Value(parcelIdIndex));  
    107.                 }  
    108.                 // Display the number of feature matching the query.  
    109.                 Console.WriteLine("Parcels found: {0}", featureClass.FeatureCount(spatialFilter));  
    110.             }  
    111.         }  
    112.   
    113.         /// <summary>  
    114.         /// This sample re-zones all "Manufacturing" parcels as "Commercial".  
    115.         /// </summary>  
    116.         /// <param name="workspace">The workspace containing the feature class.</param>  
    117.         /// <param name="featureClass">The feature class to update.</param>  
    118.         private static void UpdateCursorDemo(IWorkspace workspace, IFeatureClass featureClass)  
    119.         {  
    120.             // Create a new query filter for the update.  
    121.             IQueryFilter queryFilter = new QueryFilterClass { WhereClause = "ZONING_S = 'M'" };  
    122.   
    123.             // Display the feature's zoned as Manufacturing.  
    124.             Console.WriteLine("Parcel found zoned as Manufacturing: {0}", featureClass.FeatureCount(queryFilter));  
    125.   
    126.             // Find the index of the Zoning_S field. This is required for the update.  
    127.             int zoningIndex = featureClass.FindField("ZONING_S");  
    128.   
    129.             // Start a new edit session and edit operation.  
    130.             IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;  
    131.             workspaceEdit.StartEditing(true);  
    132.             workspaceEdit.StartEditOperation();  
    133.   
    134.             using (ComReleaser comReleaser = new ComReleaser())  
    135.             {  
    136.                 // Query the feature class to get a feature cursor. Since we are performing  
    137.                 // updates, we should use a non-recycling cursor.  
    138.                 IFeatureCursor featureCursor = featureClass.Update(queryFilter, false);  
    139.                 comReleaser.ManageLifetime(featureCursor);  
    140.   
    141.                 try  
    142.                 {  
    143.                     // Iterate through the query results.  
    144.                     IFeature feature = null;  
    145.                     while ((feature = featureCursor.NextFeature()) != null)  
    146.                     {  
    147.                         // Change the feature's ZONING_S value to "B" (the code for Business/Commercial).  
    148.                         feature.set_Value(zoningIndex, "B");  
    149.   
    150.                         // Update the feature.  
    151.                         featureCursor.UpdateFeature(feature);  
    152.                     }  
    153.   
    154.                     // All of the features were successfully updated; stop the edit operation  
    155.                     // and stop the edit session, saving the changes made in edit operations.  
    156.                     workspaceEdit.StopEditOperation();  
    157.                     workspaceEdit.StopEditing(true);  
    158.                 }  
    159.                 catch (COMException)  
    160.                 {  
    161.                     // An error occurred while editing. Abort the edit operation and stop the  
    162.                     // edit session, discarding any changes made in edit operations.  
    163.                     workspaceEdit.AbortEditOperation();  
    164.                     workspaceEdit.StopEditing(false);  
    165.                 }  
    166.   
    167.                 // Display the feature's zoned as Manufacturing after update.  
    168.                 Console.WriteLine("Parcel found zoned as Manufacturing after update: {0}", featureClass.FeatureCount(queryFilter));  
    169.             }  
    170.         }  
    171.   
    172.         /// <summary>  
    173.         /// This sample uses an insert cursor to create one hundred new pipe features.  
    174.         /// </summary>  
    175.         /// <param name="workspace">The workspace containing the feature class.</param>  
    176.         /// <param name="featureClass">The feature class to insert new features into.</param>  
    177.         private static void InsertCursorDemo(IWorkspace workspace, IFeatureClass featureClass)  
    178.         {  
    179.             // Find the index of the "Contractor" field. This will be edited in the new features.  
    180.             int contractorIndex = featureClass.FindField("CONTRACTOR");  
    181.   
    182.             // Put the feature class into "load-only" mode. In a File GDB, this will disable spatial  
    183.             // and attribute indexing, improving performance for data loading.  
    184.             IFeatureClassLoad featureClassLoad = (IFeatureClassLoad)featureClass;  
    185.             featureClassLoad.LoadOnlyMode = true;  
    186.   
    187.             // Start an edit session and edit operation.  
    188.             IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;  
    189.             workspaceEdit.StartEditing(true);  
    190.             workspaceEdit.StartEditOperation();  
    191.   
    192.             // Open the two text files containing the contractor's data.  
    193.             using (StreamReader geometryReader = new StreamReader(@"PipeGeo.csv"))  
    194.             using (StreamReader attributeReader = new StreamReader(@"PipeAttr.csv"))  
    195.             using (ComReleaser comReleaser = new ComReleaser())  
    196.             {  
    197.                 // Create a new insert cursor with buffering.  
    198.                 IFeatureCursor featureCursor = featureClass.Insert(true);  
    199.                 comReleaser.ManageLifetime(featureCursor);  
    200.   
    201.                 // Create a feature buffer. This will store the values common to every  
    202.                 // feature to be installed.  
    203.                 IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();  
    204.                 comReleaser.ManageLifetime(featureBuffer);  
    205.                 featureBuffer.set_Value(contractorIndex, "B Pierce");  
    206.   
    207.                 try  
    208.                 {  
    209.                     while (!geometryReader.EndOfStream && !attributeReader.EndOfStream)  
    210.                     {  
    211.                         // Read the next line from each text file.  
    212.                         String geometryData = geometryReader.ReadLine();  
    213.                         String attributeData = attributeReader.ReadLine();  
    214.   
    215.                         // Set the geometry and attribute values of the feature buffer.  
    216.                         featureBuffer.Shape = ConstructGeometryFromString(geometryData);  
    217.                         PopulateAttributeValues(featureBuffer, attributeData);  
    218.   
    219.                         // Insert a new feature using the feature buffer.  
    220.                         featureCursor.InsertFeature(featureBuffer);  
    221.                     }  
    222.   
    223.                     // Flush the cursor.  
    224.                     featureCursor.Flush();  
    225.   
    226.                     // All of the features were successfully inserted; stop the edit operation  
    227.                     // and stop the edit session, saving the changes made in edit operations.  
    228.                     workspaceEdit.StopEditOperation();  
    229.                     workspaceEdit.StopEditing(true);  
    230.                 }  
    231.                 catch (COMException)  
    232.                 {  
    233.                     // An error occurred while editing. Abort the edit operation and stop the  
    234.                     // edit session, discarding any changes made in edit operations.  
    235.                     workspaceEdit.AbortEditOperation();  
    236.                     workspaceEdit.StopEditing(false);  
    237.                 }  
    238.             }  
    239.   
    240.             // Take the class out of load-only mode.  
    241.             featureClassLoad.LoadOnlyMode = false;  
    242.         }  
    243.   
    244.         /// <summary>  
    245.         /// This method converts a comma-delimited set of numeric values into a polyline.  
    246.         /// </summary>  
    247.         /// <param name="input">A string of comma-delimited numeric values.</param>  
    248.         /// <returns>A polyline.</returns>  
    249.         private static IGeometry ConstructGeometryFromString(String input)  
    250.         {  
    251.             // Split the input string into individual values.  
    252.             String[] inputValues = input.Split(new char[] {','});  
    253.   
    254.             // Create a new polyline.  
    255.             IPolyline polyline = new PolylineClass();  
    256.             IGeometryCollection geometryCollection = (IGeometryCollection)polyline;  
    257.   
    258.             // Each set of four values represents one segment of a polyline.  
    259.             int segmentCount = inputValues.Length / 4;  
    260.             int inputValuePosition = 0;  
    261.             for (int i = 0; i < segmentCount; i++)  
    262.             {  
    263.                 // This value is required for geometry construction.  
    264.                 object missingType = Type.Missing;  
    265.   
    266.                 // Construct the segment.  
    267.                 IPoint fromPoint = new PointClass  
    268.                 {  
    269.                     X = Double.Parse(inputValues[inputValuePosition++]),  
    270.                     Y = Double.Parse(inputValues[inputValuePosition++])  
    271.                 };  
    272.                 IPoint toPoint = new PointClass  
    273.                 {  
    274.                     X = Double.Parse(inputValues[inputValuePosition++]),  
    275.                     Y = Double.Parse(inputValues[inputValuePosition++])  
    276.                 };  
    277.                 IPath path = new PathClass();  
    278.                 IPointCollection pointCollection = (IPointCollection)path;  
    279.                 pointCollection.AddPoint(fromPoint, ref missingType, ref missingType);  
    280.                 pointCollection.AddPoint(toPoint, ref missingType, ref missingType);  
    281.   
    282.                 // Add the segment to the collection.  
    283.                 geometryCollection.AddGeometry(path, ref missingType, ref missingType);  
    284.             }  
    285.   
    286.             // Return the constructed polyline.  
    287.             return polyline;  
    288.         }  
    289.   
    290.         /// <summary>  
    291.         /// Populates the inbound feature buffer with the comma-delimited values  
    292.         /// in the input string.  
    293.         /// </summary>  
    294.         /// <param name="featureBuffer">The feature buffer to populate.</param>  
    295.         /// <param name="input">A string containing attribute values.</param>  
    296.         private static void PopulateAttributeValues(IFeatureBuffer featureBuffer, String input)  
    297.         {  
    298.             // Split the input string into individual values.  
    299.             String[] inputValues = input.Split(new char[] { ',' });  
    300.   
    301.             // Set the values of the Date_Installed, material and diameter fields.  
    302.             // For the sake of simplicity, we'll hard-code the values here.  
    303.             featureBuffer.set_Value(2, inputValues[0]);  
    304.             featureBuffer.set_Value(4, inputValues[1]);  
    305.             featureBuffer.set_Value(5, inputValues[2]);  
    306.         }  
    307.     }  
    308. }  

    普通的编辑方法


    1. using System;  
    2. using System.IO;  
    3. using System.Runtime.InteropServices;  
    4. using ESRI.ArcGIS.DataSourcesGDB;  
    5. using ESRI.ArcGIS.esriSystem;  
    6. using ESRI.ArcGIS.Geodatabase;  
    7. using ESRI.ArcGIS.Geometry;  
    8.   
    9. namespace EditingDemo  
    10. {  
    11.     public class EditingDemo  
    12.     {  
    13.         public static void Main(string[] args)  
    14.         {  
    15.             #region Licensing  
    16.             // Set up the licencing. NOTE: This sample assumes that you are using ArcInfo Desktop.  
    17.             // You will need to adjust this code if using ArcEngine or ArcEditor.  
    18.             IAoInitialize aoInitialize = new AoInitializeClass();  
    19.             esriLicenseStatus licenseStatus = aoInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcInfo);  
    20.             if (licenseStatus != esriLicenseStatus.esriLicenseCheckedOut)  
    21.             {  
    22.                 Console.WriteLine("Unable to check-out an ArcInfo license, error code is {0}", licenseStatus);  
    23.                 return;  
    24.             }  
    25.             #endregion  
    26.   
    27.             // If test data exists from a previous run, delete it.  
    28.             if (Directory.Exists("EditingDemo.gdb"))  
    29.             {  
    30.                 Directory.Delete("EditingDemo.gdb"true);  
    31.             }  
    32.   
    33.             // Copy the test data from this section's Data directory.  
    34.             Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");  
    35.             IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);  
    36.             IWorkspaceName sourceWorkspaceName = new WorkspaceNameClass();  
    37.             sourceWorkspaceName.PathName = @"..\..\..\Data\EditingDemo.gdb";  
    38.             sourceWorkspaceName.WorkspaceFactoryProgID = "esriDataSourcesGDB.FileGDBWorkspaceFactory";  
    39.             IWorkspaceName copiedWorkspaceName = null;  
    40.             workspaceFactory.Copy(sourceWorkspaceName, Environment.CurrentDirectory, out copiedWorkspaceName);  
    41.   
    42.             // Open the copied data.  
    43.             IName copiedName = (IName)copiedWorkspaceName;  
    44.             IWorkspace workspace = (IWorkspace)copiedName.Open();  
    45.             IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;  
    46.             IFeatureClass featureClass = featureWorkspace.OpenFeatureClass("Points");  
    47.   
    48.             // Create two points: one with valid coordinates, one with invalid coordinates.  
    49.             // Note that the data uses a geographic coordinate system.  
    50.             IPoint validPoint = new PointClass { X = 45, Y = 45 };  
    51.             IPoint invalidPoint = new PointClass { X = 1000, Y = -1000 };  
    52.   
    53.             // Start an edit session and an edit operation.  
    54.             IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;  
    55.             workspaceEdit.StartEditing(true);  
    56.             workspaceEdit.StartEditOperation();  
    57.   
    58.             // Create a new feature using the valid point.  
    59.             try  
    60.             {  
    61.                 IFeature feature = featureClass.CreateFeature();  
    62.                 feature.Shape = validPoint;  
    63.                 feature.Store();  
    64.   
    65.                 // Stop the edit operation.  
    66.                 workspaceEdit.StopEditOperation();  
    67.             }  
    68.             catch (COMException comExc)  
    69.             {  
    70.                 Console.WriteLine("An error occurred ({0}): {1}", comExc.ErrorCode, comExc.Message);  
    71.   
    72.                 // Abort the edit operation.  
    73.                 workspaceEdit.AbortEditOperation();  
    74.             }  
    75.   
    76.             // Create a new feature using the invalid point.  
    77.             try  
    78.             {  
    79.                 IFeature feature = featureClass.CreateFeature();  
    80.                 feature.Shape = invalidPoint;  
    81.                 feature.Store();  
    82.   
    83.                 // Stop the edit operation.  
    84.                 workspaceEdit.StopEditOperation();  
    85.             }  
    86.             catch (COMException comExc)  
    87.             {  
    88.                 Console.WriteLine("An error occurred ({0}): {1}", comExc.ErrorCode, comExc.Message);  
    89.   
    90.                 // Abort the edit operation.  
    91.                 workspaceEdit.AbortEditOperation();  
    92.             }  
    93.   
    94.             // Stop the edit operation, saving the changes from any committed edit operations.  
    95.             workspaceEdit.StopEditing(true);  
    96.   
    97.             // Shut down the licensing.  
    98.             aoInitialize.Shutdown();  
    99.         }  
    100.     }  
    101. }  

标签: arcgis二次开发 arcgis Geodatabase

WRITTEN BY

avatar