ArcGIS Engine 개발 Geodatabase 코드 (3) - Data Loading

8830 단어
/******************************************/ * 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: GP 도구를 직접 호출하는 Copy Feature
    2: IFeatureDataConverter를 사용한 변환
    설명: ArcCatalog를 사용하여 데이터 가져오기 내보내기에 두 가지 방법을 사용한 적이 있습니다.
    1:Copy/Paste
    이 방법은 사실 Copy Feature를 호출하는 것이다. 이런 방법은 데이터 집합에 포함된 고급 대상(토폴로지, 기하학적 네트워크, 관계 클래스 등)을 모두paste할 수 있고 ObjectID를 다시 배열하지 않는다.
    정정하다
    이 방법은 사실 Copy를 호출하는 것이다. 이런 방법은 데이터 집합에 고급 대상(토폴로지, 기하학적 네트워크, 관계 클래스 등)을 포함하여paste를 직접 할 수 있고 ObjectID를 다시 배열하지 않는다.
    Copy 툴은 전체 데이터 세트 복제본입니다.
    Copy Feature 툴은 요소 클래스 복제본입니다.
    2:Import/Export
    이 방법은 요소 클래스를 가져오고 내보내는 것입니다. 그러면 고급 대상은 가져오고 내보내지 않으며 ObjectID는 다시 배열됩니다.
    그래서 사용하면서 다른 방법을 선택할 수 있어요.
    첫 번째 방법:
    using System;
    using System.IO;
    using ESRI.ArcGIS.DataManagementTools;
    using ESRI.ArcGIS.esriSystem;
    using ESRI.ArcGIS.Geodatabase;
    using ESRI.ArcGIS.Geoprocessor;
    
    namespace CopyFeaturesDemo  
    {
    	public class CopyFeaturesDemo
    	{
    		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
    
    			#region Data Setup
    			// If any GDB test data is leftover from previous runs, delete it.
    			if (Directory.Exists("LoadTarget.gdb"))
    			{
    				Directory.Delete("LoadTarget.gdb", true);
    			}
    
    			// Create a new File GDB as a target for the copy.
    			Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
    			IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
    			workspaceFactory.Create(Environment.CurrentDirectory, "LoadTarget", null, 0);
    			#endregion
    
    			// Intialize the Geoprocessor.
                Geoprocessor geoprocessor = new Geoprocessor();
    
    			// Set the overwrite output option to true.
    			geoprocessor.OverwriteOutput = true;
    
                 // Intialize the CopyFeatures tool.
                 CopyFeatures copyFeatures = new CopyFeatures
    			{
    				in_features = Path.Combine(Environment.CurrentDirectory, @"..\..\..\Data\Buildings.shp"),
    				out_feature_class = Path.Combine(Environment.CurrentDirectory, @"LoadTarget.gdb\Buildings_GP")
    			};
    
    			// Run the tool.
    			try
    			{
    				geoprocessor.Execute(copyFeatures, null);
    				Console.WriteLine("CopyFeatures completed.");
    			}
    			catch (Exception exc)
    			{
    				Console.WriteLine("CopyFeatures failed.");
    				Console.WriteLine("Exception message: {0}", exc.Message);
    			}
    			finally
    			{
    				// Display the geoprocessor's output.
    				for (int i = 0; i < geoprocessor.MessageCount; i++)
    				{
    					Console.WriteLine(geoprocessor.GetMessage(i));
    				}
    			}
        }
    	}
    }
    

    두 번째 방법
    using System;
    using System.Runtime.InteropServices;
    using ESRI.ArcGIS.esriSystem;
    using ESRI.ArcGIS.Geodatabase;
    using ESRI.ArcGIS.DataSourcesFile;
    using ESRI.ArcGIS.DataSourcesGDB;
    
    namespace FDConverterDemo
    {
        public class FDConverterDemo
        {
            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
    
              try
              {
    						// Create a name object for the source workspace.
    						IWorkspaceName sourceWorkspaceName = new WorkspaceNameClass
    						{
    							PathName = @"..\..\..\Data",
    							WorkspaceFactoryProgID = "esriDataSourcesFile.ShapefileWorkspaceFactory"
    						};
    
    						// Create and open a new Geodatabase for the data.
    						Type targetFactoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
    						IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(targetFactoryType);
    						IWorkspaceName targetWorkspaceName = workspaceFactory.Create(Environment.CurrentDirectory, "LoadTarget", null, 0);
                
                              // Create a name object for the source feature class.
    						IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
    						IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName;
                             sourceDatasetName.WorkspaceName = sourceWorkspaceName;
                             sourceDatasetName.Name = "Buildings.shp";
    
    						// Create a name object for the feature class to be created.
    						IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
    						IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName;
    						targetDatasetName.WorkspaceName = targetWorkspaceName;
    						targetDatasetName.Name = "Buildings_FDC";
                
                            // Open the source feature class to get field definitions.
                            IName sourceName = (IName)sourceDatasetName;
                            IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();
    
    						// Open the two workspaces for the field validator.
    						IName sourceIName = (IName)sourceWorkspaceName;
    						IName targetIName = (IName)targetWorkspaceName;
    						IWorkspace sourceWorkspace = (IWorkspace)sourceIName.Open();
    						IWorkspace targetWorkspace = (IWorkspace)targetIName.Open();
    
                            // Use a field checker for field validation.
                            IFieldChecker fieldChecker = new FieldCheckerClass();
    						IFields sourceFields = sourceFeatureClass.Fields;
    						fieldChecker.InputWorkspace = sourceWorkspace;
    						fieldChecker.ValidateWorkspace = targetWorkspace;
    						IEnumFieldError enumFieldError = null;
    						IFields outputFields = null;
                            fieldChecker.Validate(sourceFields, out enumFieldError, out outputFields);
    
    						// If any field validation errors occurred, they can be viewed at this point.
    
                            // Get the GeometryDef from the source feature class and modify it.
    						// Note that this only modifies the object in memory, and will not effect the source data.
    						int shapeFieldIndex = sourceFeatureClass.FindField(sourceFeatureClass.ShapeFieldName);
    						IField shapeField = sourceFields.get_Field(shapeFieldIndex);
    						IGeometryDef geometryDef = shapeField.GeometryDef;
    						IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
    						geometryDefEdit.GridCount_2 = 1;
    						geometryDefEdit.set_GridSize(0, 20);
    
    						// Load the feature class.
    						IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass();
    						IEnumInvalidObject enumInvalidObject = featureDataConverter.ConvertFeatureClass(sourceFeatureClassName, 
    							null, null, targetFeatureClassName, geometryDef, outputFields, "", 1000, 0);
    
    						// If any invalid features were encountered during conversion, they can be
    						// displayed by iterating through the enumInvalidObject enumerator.
              }
              catch (COMException comExc)
              {
    						Console.WriteLine("An error occurred ({0}): {1}", comExc.ErrorCode, comExc.Message);
              }
              catch (Exception exc)
              {
    						Console.WriteLine("An error occurred: {0}", exc.Message);
              }
              finally
              {
    						Console.WriteLine("Done.");
              }
          }
        }
    }
    

    좋은 웹페이지 즐겨찾기