ArcGIS Engine开发Geodatabase代码(二)——DataAccess and Creation

/******************************************/
 * ESRI Developer Summit 2009
 * Developer's Guide to the Geodatabase
 * Code Samples
 * 6 April 2009

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

偶然间整理电脑的文件夹,发现在Esri官网上曾经下载过关于Geodatabase开发的相关代码示例,赶紧跟各位共享一下

开发环境:

  • ArcGIS Engine9.3/9.3.1
  • VS2008


说明:该代码适用于ArcGIS Engine初学者,或者对Geodatabase开发感兴趣的朋友,如果你的Engine版本高于9.3.1,可能相关的接口会发生变化,这个需要用户自己来进行修改,但是聪明的用户不会局限于代码的是否允许,也许学习一下人家的接口使用方法,开发模式才是最重要的。

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


以下代码主要实现功能

1:创建FileGeodatabase

2:创建要素类

3:创建域对象

4:创建子类

5:创建要素

using System;
using System.IO;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;

namespace DataAccessDemo
{
	public class DataAccessDemo
	{
		public static void Main(string[] args)
		{
			#region Licensing
			// Set up the licencing. NOTE: This sample assumes that you are using ArcInfo Desktop.
			// You will need to adjust this code if using ArcEngine or ArcEditor.
			IAoInitialize aoInitialize = new AoInitializeClass();
			esriLicenseStatus licenseStatus = aoInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcInfo);
			if (licenseStatus != esriLicenseStatus.esriLicenseCheckedOut)
			{
				Console.WriteLine("Unable to check-out an ArcInfo license, error code is {0}", licenseStatus);
				return;
			}
			#endregion

			// If existing data is leftover from a previous run, delete it.
			if (Directory.Exists("DataAccessDemo.gdb"))
			{
				Directory.Delete("DataAccessDemo.gdb", true);
			}

			// The first demo, CreateFileGdbDemo, will create a new File geodatabase and return
			// an IWorkspace reference for the second demo to use.
			IWorkspace workspace = CreateFileGdbDemo();

			// The second demo, CreateFeatureClassDemo, will create and return a new feature class.
			IFeatureClass featureClass = CreateFeatureClassDemo(workspace);

			// The third demo, CreateDomainsDemo, will create several domains in the workspace.
			CreateDomainsDemo(workspace);

			// The fourth demo, CreateSubtypesDemo, will create subtypes in the feature class created earlier.
			IWorkspaceDomains workspaceDomains = (IWorkspaceDomains)workspace;
			CreateSubtypesDemo(workspaceDomains, featureClass);

			// The fifth demo, CreateFeatureDemo, will create a single feature in the feature class.
			CreateFeatureDemo(workspace, featureClass);

			// Shutdown the application licensing.
			aoInitialize.Shutdown();
		}

		/// <summary>
		/// This sample creates a new File Geodatabase in the working directory.
		/// </summary>
		/// <returns>An IWorkspace reference to the newly-created geodatabase.</returns>
		private static IWorkspace CreateFileGdbDemo()
		{
			// Instantiate a File GDB workspace factory and use it to create a new File GDB in the
			// section's Data directory.
			Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
			IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
			IWorkspaceName workspaceName = workspaceFactory.Create(Environment.CurrentDirectory, "DataAccessDemo", null, 0);

			// We can open the workspace using the name object.
			IName name = (IName)workspaceName;
			IWorkspace workspace = (IWorkspace)name.Open();

			// Display the path of the new workspace.
			Console.WriteLine("Path of the new File GDB: {0}", workspace.PathName);

			return workspace;
		}

		/// <summary>
		/// This sample creates a new feature dataset and feature class.
		/// </summary>
		/// <param name="workspace">The workspace to create the feature dataset and feature class in.</param>
		/// <returns>An IFeatureClass reference to the newly-created feature class.</returns>
		private static IFeatureClass CreateFeatureClassDemo(IWorkspace workspace)
		{
			// To create new datasets in a workspace, the IFeatureWorkspace interface is required.
			IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;

			#region Create a spatial reference for the feature dataset.
			// Create a spatial reference for the feature dataset.
			ISpatialReferenceFactory spatialRefFactory = new SpatialReferenceEnvironmentClass();
			ISpatialReference spatialReference = spatialRefFactory.CreateProjectedCoordinateSystem
				((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_20N);

			// Determine whether the workspace supports high-precision storage.
			Boolean supportsHighPrecision = false;
			IWorkspaceProperties workspaceProperties = (IWorkspaceProperties)workspace;
			IWorkspaceProperty workspaceProperty = workspaceProperties.get_Property
				(esriWorkspacePropertyGroupType.esriWorkspacePropertyGroup,
				(int)esriWorkspacePropertyType.esriWorkspacePropSupportsHighPrecisionStorage);
			if (workspaceProperty.IsSupported)
			{
				supportsHighPrecision = Convert.ToBoolean(workspaceProperty.PropertyValue);
			}

			// Set the precision of the spatial reference.
			IControlPrecision2 controlPrecision = (IControlPrecision2)spatialReference;
			controlPrecision.IsHighPrecision = supportsHighPrecision;
			
			// Set the resolution and tolerance of the spatial reference.
			ISpatialReferenceResolution spatialRefResolution = (ISpatialReferenceResolution)spatialReference;
			spatialRefResolution.ConstructFromHorizon();
			spatialRefResolution.SetDefaultXYResolution();
			ISpatialReferenceTolerance spatialRefTolerance = (ISpatialReferenceTolerance)spatialReference;
			spatialRefTolerance.SetDefaultXYTolerance();
			#endregion

			// Create the feature dataset.
			IFeatureDataset featureDataset = featureWorkspace.CreateFeatureDataset("DemoDataset", spatialReference);

			// Use a feature class description object to get the required fields for a
			// new feature class.
			IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
			IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;
			IFields fields = ocDescription.RequiredFields;
			IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

			// By default, the GeometryDef provided by a feature class description specifies that
			// a feature class should contain polygon features. Change it to polylines.
			int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
			IField shapeField = fields.get_Field(shapeFieldIndex);
			IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)shapeField.GeometryDef;
			geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;

			// If the workspace doesn't support high-precision storage, change the precision of the
			// GeometryDef's spatial reference.
			if (!supportsHighPrecision)
			{
				IControlPrecision2 geoDefPrecision = (IControlPrecision2)geometryDefEdit.SpatialReference;
				geoDefPrecision.IsHighPrecision = false;
			}

			// Add a small integer field called "PipeType" to the fields collection.
			IField field = new FieldClass();
			IFieldEdit fieldEdit = (IFieldEdit)field;
			fieldEdit.Name_2 = "PipeType";
			fieldEdit.Type_2 = esriFieldType.esriFieldTypeSmallInteger;
			fieldsEdit.AddField(field);

			#region Add some more fields...
			// Add a small integer field called "Material" to the fields collection.
			field = new FieldClass();
			fieldEdit = (IFieldEdit)field;
			fieldEdit.Name_2 = "Material";
			fieldEdit.AliasName_2 = "Pipe Material";
			fieldEdit.Type_2 = esriFieldType.esriFieldTypeSmallInteger;
			fieldEdit.IsNullable_2 = true;
			fieldsEdit.AddField(field);

			// Add a small integer field called "Diameter" to the fields collection.
			field = new FieldClass();
			fieldEdit = (IFieldEdit)field;
			fieldEdit.Name_2 = "Diameter";
			fieldEdit.AliasName_2 = "Pipe Diameter";
			fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
			fieldEdit.IsNullable_2 = true;
			fieldsEdit.AddField(field);

			// Add a string field called "InstBy" to the fields collection.
			field = new FieldClass();
			fieldEdit = (IFieldEdit)field;
			fieldEdit.Name_2 = "InstBy";
			fieldEdit.AliasName_2 = "Installed By";
			fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
			fieldEdit.Length_2 = 75;
			fieldEdit.IsNullable_2 = true;
			fieldEdit.DefaultValue_2 = "K. Johnston";
			fieldsEdit.AddField(field);
			#endregion

			// Create the feature class using the fields collection that was just created.
			IFeatureClass featureClass = featureDataset.CreateFeatureClass("DemoClass", fields,
				ocDescription.InstanceCLSID, null, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, String.Empty);

			// Return the newly-created feature class.
			return featureClass;
		}

		/// <summary>
		/// This sample creates several domains in the specified workspace.
		/// </summary>
		/// <param name="workspace">The workspace to create the domains in.</param>
		private static void CreateDomainsDemo(IWorkspace workspace)
		{
			// The IWorkspaceDomains interface is required to add domains to a workspace.
			IWorkspaceDomains workspaceDomains = (IWorkspaceDomains)workspace;

			// Create a new coded value domain for primary pipe materials.
			ICodedValueDomain primaryMaterialCVDomain = new CodedValueDomainClass();
			IDomain primaryMaterialDomain = (IDomain)primaryMaterialCVDomain;
			primaryMaterialCVDomain.AddCode(1, "Copper");
			primaryMaterialCVDomain.AddCode(2, "Steel");
			primaryMaterialCVDomain.AddCode(3, "Concrete");
			primaryMaterialDomain.Name = "PrimMats";
			primaryMaterialDomain.Description = "Valid materials for primary pipes.";
			primaryMaterialDomain.FieldType = esriFieldType.esriFieldTypeSmallInteger;
			primaryMaterialDomain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;
			primaryMaterialDomain.SplitPolicy = esriSplitPolicyType.esriSPTDuplicate;
			workspaceDomains.AddDomain(primaryMaterialDomain);

			// Create a new range domain for primary pipe diameters.
			IRangeDomain primaryDiameterRangeDomain = new RangeDomainClass();
			IDomain primaryDiameterDomain = (IDomain)primaryDiameterRangeDomain;
			primaryDiameterRangeDomain.MaxValue = 10;
			primaryDiameterRangeDomain.MinValue = 2.5;
			primaryDiameterDomain.Name = "PrimDiam";
			primaryDiameterDomain.Description = "Valid diameters (in inches) for primary pipes.";
			primaryDiameterDomain.FieldType = esriFieldType.esriFieldTypeDouble;
			primaryDiameterDomain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;
			primaryDiameterDomain.SplitPolicy = esriSplitPolicyType.esriSPTDuplicate;
			workspaceDomains.AddDomain(primaryDiameterDomain);

			#region Add secondary pipe domains...
			// Create a new coded value domain for secondary pipe materials.
			ICodedValueDomain secondaryMaterialCVDomain = new CodedValueDomainClass();
			IDomain secondaryMaterialDomain = (IDomain)secondaryMaterialCVDomain;
			secondaryMaterialCVDomain.AddCode(1, "Copper");
			secondaryMaterialCVDomain.AddCode(2, "Steel");
			secondaryMaterialCVDomain.AddCode(3, "PVC");
			secondaryMaterialDomain.Name = "SecMats";
			secondaryMaterialDomain.Description = "Valid materials for secondary pipes.";
			secondaryMaterialDomain.FieldType = esriFieldType.esriFieldTypeSmallInteger;
			secondaryMaterialDomain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;
			secondaryMaterialDomain.SplitPolicy = esriSplitPolicyType.esriSPTDuplicate;
			workspaceDomains.AddDomain(secondaryMaterialDomain);

			// Create a new range domain for secondary pipe diameters.
			IRangeDomain secondaryDiameterRangeDomain = new RangeDomainClass();
			IDomain secondaryDiameterDomain = (IDomain)secondaryDiameterRangeDomain;
			secondaryDiameterRangeDomain.MaxValue = 7.5;
			secondaryDiameterRangeDomain.MinValue = 1;
			secondaryDiameterDomain.Name = "SecDiam";
			secondaryDiameterDomain.Description = "Valid diameters (in inches) for secondary pipes.";
			secondaryDiameterDomain.FieldType = esriFieldType.esriFieldTypeDouble;
			secondaryDiameterDomain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;
			secondaryDiameterDomain.SplitPolicy = esriSplitPolicyType.esriSPTDuplicate;
			workspaceDomains.AddDomain(secondaryDiameterDomain);
			#endregion
		}

		/// <summary>
		/// This sample creates subtypes in the specified feature class. The fields of the subtypes are
		/// assigned domains from the workspace.
		/// </summary>
		/// <param name="workspaceDomains">The workspace of the feature class.</param>
		/// <param name="featureClass">The feature class to create subtypes in.</param>
		private static void CreateSubtypesDemo(IWorkspaceDomains workspaceDomains, IFeatureClass featureClass)
		{
			// Cast the feature class to the ISchemaLock interface, because we are making a
			// schema change in an existing dataset.
			ISchemaLock schemaLock = (ISchemaLock)featureClass;
			try
			{
				// Attempt to acquire an exclusive lock on the feature class. This will raise an
				// exception if it fails.
				schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);

				// Cast the feature class to the ISubtypes interface and setup the subtype field.
				ISubtypes subtypes = (ISubtypes)featureClass;
				subtypes.SubtypeFieldName = "PipeType";
				subtypes.AddSubtype(1, "Primary");
				subtypes.AddSubtype(2, "Secondary");
				subtypes.DefaultSubtypeCode = 1;

				// Setup the default values and domains for primary pipes.
				subtypes.set_DefaultValue(1, "Diameter", 10);
				subtypes.set_DefaultValue(1, "Material", 2);
				subtypes.set_Domain(1, "Diameter", workspaceDomains.get_DomainByName("PrimDiam"));
				subtypes.set_Domain(1, "Material", workspaceDomains.get_DomainByName("PrimMats"));

				// Setup the default values and domains for secondary pipes.
				subtypes.set_DefaultValue(2, "Diameter", 7.5);
				subtypes.set_DefaultValue(2, "Material", 2);
				subtypes.set_Domain(2, "Diameter", workspaceDomains.get_DomainByName("SecDiam"));
				subtypes.set_Domain(2, "Material", workspaceDomains.get_DomainByName("SecMats"));
			}
			catch (COMException comExc)
			{
				Console.WriteLine("An error occurred while attempting to add subtypes to the feature class.");
				Console.WriteLine("{0} ({1})", comExc.Message, comExc.ErrorCode);
			}
			finally
			{
				// Regardless of what happened, make sure the schema lock is set to a shared lock.
				schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
			}
		}

		/// <summary>
		/// This sample creates a new feature in the provided feature class, setting the subtype field
		/// and the subtype's default values.
		/// </summary>
		/// <param name="workspace">The workspace containing the feature class.</param>
		/// <param name="featureClass">The feature class to create the feature in.</param>
		public static void CreateFeatureDemo(IWorkspace workspace, IFeatureClass featureClass)
		{
			// Create a shape for the new feature.
			IPoint fromPoint = new PointClass { X = 500000, Y = 0 };
			IPoint toPoint = new PointClass { X = 500050, Y = -50 };
			IPolyline polyline = new PolylineClass { FromPoint = fromPoint, ToPoint = toPoint };

			// Get the indexes of the fields to edit in the feature class.
			int pipeTypeIndex = featureClass.FindField("PipeType");
			int materialIndex = featureClass.FindField("Material");
			int diameterIndex = featureClass.FindField("Diameter");
			int instByIndex = featureClass.FindField("InstBy");

			// Start an edit session and an edit operation.
			IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;
			workspaceEdit.StartEditing(true);
			workspaceEdit.StartEditOperation();

			// Create a new feature and set its shape.
			IFeature feature = featureClass.CreateFeature();
			feature.Shape = polyline;

			// Use the IRowSubtypes interface to set the subtype code and the subtype default values.
			IRowSubtypes rowSubtypes = (IRowSubtypes)feature;
			rowSubtypes.SubtypeCode = 1;

			// Display the attribute values of the feature at this point. Note that the
			// subtype defaults have not been applied by setting the subtype code.
			Console.WriteLine("OID: {0}, PipeType: {1}, Material: {2}, Diameter: {3}, InstBy: {4}",
				feature.OID, feature.get_Value(pipeTypeIndex), feature.get_Value(materialIndex),
				feature.get_Value(diameterIndex), feature.get_Value(instByIndex));

			// Apply the default subtype values.
			rowSubtypes.InitDefaultValues();

			// Display the feature's values, now set to the subtype defaults.
			Console.WriteLine("OID: {0}, PipeType: {1}, Material: {2}, Diameter: {3}, InstBy: {4}",
				feature.OID, feature.get_Value(pipeTypeIndex), feature.get_Value(materialIndex),
				feature.get_Value(diameterIndex), feature.get_Value(instByIndex));

			// Set the attribute values that need to be changed.
			feature.set_Value(instByIndex, "B. Pierce");

			// Display the feature's new values.
			Console.WriteLine("OID: {0}, PipeType: {1}, Material: {2}, Diameter: {3}, InstBy: {4}",
				feature.OID, feature.get_Value(pipeTypeIndex), feature.get_Value(materialIndex),
				feature.get_Value(diameterIndex), feature.get_Value(instByIndex));

			// Store the feature.
			feature.Store();

			// Stop the edit operation and edit session.
			workspaceEdit.StopEditOperation();
			workspaceEdit.StopEditing(true);
		}
	}
}


源代码下载

你可能感兴趣的:(ArcGIS Engine开发Geodatabase代码(二)——DataAccess and Creation)