private ISpatialReference GetSpatialReference(int xyCoordinateSystem) { const bool IsHighPrecision = true; ISpatialReference spatialReference; ISpatialReferenceFactory3 spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); spatialReference = spatialReferenceFactory.CreateSpatialReference(xyCoordinateSystem); IControlPrecision2 controlPrecision = spatialReference as IControlPrecision2; controlPrecision.IsHighPrecision = IsHighPrecision; ISpatialReferenceResolution spatialReferenceResolution = spatialReference as ISpatialReferenceResolution; spatialReferenceResolution.ConstructFromHorizon(); spatialReferenceResolution.SetDefaultXYResolution(); spatialReferenceResolution.SetDefaultZResolution(); spatialReferenceResolution.SetDefaultMResolution(); ISpatialReferenceTolerance spatialReferenceTolerance = spatialReference as ISpatialReferenceTolerance; spatialReferenceTolerance.SetDefaultXYTolerance(); spatialReferenceTolerance.SetDefaultZTolerance(); spatialReferenceTolerance.SetDefaultMTolerance(); return(spatialReference); }
public static void ChangeCoordinateSystem(IGeodatabaseRelease igeodatabaseRelease_0, ISpatialReference ispatialReference_0, bool bool_0) { if (ispatialReference_0 != null) { bool geoDatasetPrecision = GeodatabaseTools.GetGeoDatasetPrecision(igeodatabaseRelease_0); IControlPrecision2 controlPrecision = ispatialReference_0 as IControlPrecision2; if (controlPrecision.IsHighPrecision != geoDatasetPrecision) { controlPrecision.IsHighPrecision = geoDatasetPrecision; double num; double num2; double num3; double num4; ispatialReference_0.GetDomain(out num, out num2, out num3, out num4); if (bool_0) { ISpatialReferenceResolution spatialReferenceResolution = ispatialReference_0 as ISpatialReferenceResolution; spatialReferenceResolution.ConstructFromHorizon(); spatialReferenceResolution.SetDefaultXYResolution(); ISpatialReferenceTolerance spatialReferenceTolerance = ispatialReference_0 as ISpatialReferenceTolerance; spatialReferenceTolerance.SetDefaultXYTolerance(); } } } }
/// <summary> // 创建要素数据集 /// </summary> /// <param name="workspace"></param> /// <param name="code"></param> /// <param name="datasetName"></param> /// <returns></returns> public IFeatureDataset CreateFeatureClass(IWorkspace workspace, int code, string datasetName) { IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace; //创建一个要素集创建一个投影 ISpatialReferenceFactory spatialRefFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = spatialRefFactory.CreateProjectedCoordinateSystem(code); //确定是否支持高精度存储空间 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); } //设置投影精度 IControlPrecision2 controlPrecision = (IControlPrecision2)spatialReference; controlPrecision.IsHighPrecision = supportsHighPrecision; //设置容差 ISpatialReferenceResolution spatialRefResolution = (ISpatialReferenceResolution)spatialReference; spatialRefResolution.ConstructFromHorizon(); spatialRefResolution.SetDefaultXYResolution(); ISpatialReferenceTolerance spatialRefTolerance = (ISpatialReferenceTolerance)spatialReference; spatialRefTolerance.SetDefaultXYTolerance(); //创建要素集 IFeatureDataset featureDataset = featureWorkspace.CreateFeatureDataset(datasetName, spatialReference); return(featureDataset); }
/// <summary> /// 创建要素集 20110919 xisheng /// </summary> /// <param name="feaworkspace">指定工作空间</param> /// <param name="datasetname">指定要素集名称</param> /// <param name="PrjPath">空间参考</param> /// <returns></returns> private static IFeatureDataset CreateFeatureDataset(IFeatureWorkspace feaworkspace, string datasetname, string PrjPath) { try { string spatialPath = PrjPath; ISpatialReferenceFactory pSpaReferenceFac = new SpatialReferenceEnvironmentClass(); //空间参考工厂 ISpatialReference pSpatialReference = null; //用来获得空间参考 if (File.Exists(spatialPath)) { pSpatialReference = pSpaReferenceFac.CreateESRISpatialReferenceFromPRJFile(spatialPath); } if (pSpatialReference == null) { pSpatialReference = new UnknownCoordinateSystemClass(); } //设置默认的Resolution ISpatialReferenceResolution pSpatiaprefRes = pSpatialReference as ISpatialReferenceResolution; pSpatiaprefRes.ConstructFromHorizon();//Defines the XY resolution and domain extent of this spatial reference based on the extent of its horizon pSpatiaprefRes.SetDefaultXYResolution(); pSpatiaprefRes.SetDefaultZResolution(); pSpatiaprefRes.SetDefaultMResolution(); //设置默认的Tolerence ISpatialReferenceTolerance pSpatialrefTole = pSpatiaprefRes as ISpatialReferenceTolerance; pSpatialrefTole.SetDefaultXYTolerance(); pSpatialrefTole.SetDefaultZTolerance(); pSpatialrefTole.SetDefaultMTolerance(); //创建数据集 IFeatureDataset pFeatureDataset = null;//定义数据集用来装载要素类 pFeatureDataset = feaworkspace.CreateFeatureDataset(datasetname, pSpatialReference); return(pFeatureDataset); } catch (Exception e) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(e, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(e, null, DateTime.Now); } //******************************************************************** return(null); } }
public IFeatureClass CreateFeatureClassToAccessDB(string featureClassName, UID classExtensionUID, IFeatureWorkspace featureWorkspace) { //创建字段集合 IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields; //定义单个的字段 IField pField = new FieldClass(); IFieldEdit pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "OID"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; pFieldsEdit.AddField(pField); //为要素类创建几何定义和空间参考 IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit pGeoDefEdit = geometryDef as IGeometryDefEdit; pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; //指定创建的要素类的要素类型 ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_Beijing1954); ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); pGeoDefEdit.SpatialReference_2 = spatialReference; //设置要素类的空间参考 //将几何字段添加到字段集合 IField geometryField = new FieldClass(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; pFieldsEdit.AddField(geometryField); //创建字段name IField nameField = new FieldClass(); IFieldEdit nameFieldEdit = (IFieldEdit)nameField; nameFieldEdit.Name_2 = "Name"; nameFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; nameFieldEdit.Length_2 = 20; pFieldsEdit.AddField(nameField); IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, pFields, null, classExtensionUID, esriFeatureType.esriFTSimple, "Shape", ""); return(featureClass); }
public static ISpatialReference ConstructCoordinateSystem(IGeodatabaseRelease igeodatabaseRelease_0) { bool geoDatasetPrecision = GeodatabaseTools.GetGeoDatasetPrecision(igeodatabaseRelease_0); ISpatialReference spatialReference = new UnknownCoordinateSystem() as ISpatialReference; IControlPrecision2 controlPrecision = spatialReference as IControlPrecision2; controlPrecision.IsHighPrecision = geoDatasetPrecision; ISpatialReferenceResolution spatialReferenceResolution = spatialReference as ISpatialReferenceResolution; spatialReferenceResolution.ConstructFromHorizon(); spatialReferenceResolution.SetDefaultXYResolution(); ISpatialReferenceTolerance spatialReferenceTolerance = spatialReference as ISpatialReferenceTolerance; spatialReferenceTolerance.SetDefaultXYTolerance(); return(spatialReference); }
/// <summary> /// 创建几何空间参考 /// </summary> /// <param name="LoadPath">空间参考文件</param> /// <param name="eError"></param> /// <returns></returns> public ISpatialReference GetSpatialRef(string LoadPath, out Exception eError) { eError = null; try { ISpatialReference pSR = null; ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass(); if (!File.Exists(LoadPath)) { //eError = new Exception("空间参考文件不存在!"); return(null); } pSR = pSpatialRefFac.CreateESRISpatialReferenceFromPRJFile(LoadPath); ISpatialReferenceResolution pSRR = pSR as ISpatialReferenceResolution; ISpatialReferenceTolerance pSRT = (ISpatialReferenceTolerance)pSR; IControlPrecision2 pSpatialPrecision = (IControlPrecision2)pSR; pSRR.ConstructFromHorizon();//Defines the XY resolution and domain extent of this spatial reference based on the extent of its horizon pSRR.SetDefaultXYResolution(); pSRT.SetDefaultXYTolerance(); return(pSR); } catch (Exception ex) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(ex, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(ex, null, DateTime.Now); } //******************************************************************** eError = ex; return(null); } }
/// <summary> /// Creates the fields for the ESRI geodatabase featureclass from the spatialite table /// </summary> /// <returns>IFields to use when building the featureclass</returns> private IFields CreateFields() { IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; // Add an object ID field to the fields collection. This is mandatory for feature classes. IField oidField = new FieldClass(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); // Create a geometry definition (and spatial reference) for the feature class. IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = GetEsriGeometryType(); ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = CreateSpatialReference(); ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Add a geometry field to the fields collection. This is where the geometry definition is applied. IField geometryField = new FieldClass(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); CreateSpatialiteFields(ref fieldsEdit); return(fields); }
/// <summary> /// 建立featureclass /// </summary> /// <param name="featureClassName"></param> /// <returns></returns> public IFeatureClass CreateFC(string featureClassName) { if (pWorkspace == null) { throw new NullReferenceException("尚未建立Wokspace, " + nameof(pWorkspace) + " NullReference"); } IFeatureClass pFC = null; UID pCLSID = null; if (pCLSID == null) { pCLSID = new UID(); pCLSID.Value = "esriGeoDatabase.Feature"; } IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace; IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass(); // create the fields using the required fields method IFields fields = objectClassDescription.RequiredFields; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; // Create a geometry definition (and spatial reference) for the feature class. // GeometryType=point and SpatialReference=WGS84 IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Set spatialReference for (int i = 0; i < fields.FieldCount; i++) { var pfield = fields.get_Field(i); if (pfield.Type == esriFieldType.esriFieldTypeGeometry) { var geometryField = pfield as IFieldEdit; geometryField.GeometryDef_2 = geometryDef; Console.WriteLine(pfield.GeometryDef.SpatialReference.Name); break; } } // create a user defined text field IField field = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)field; // setup field properties fieldEdit.Name_2 = "SampleField"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.IsNullable_2 = true; fieldEdit.AliasName_2 = "Sample Field Column"; fieldEdit.DefaultValue_2 = "test"; fieldEdit.Editable_2 = true; fieldEdit.Length_2 = 100; // add field to field collection fieldsEdit.AddField(field); fields = (IFields)fieldsEdit; String strShapeField = ""; // locate the shape field for (int j = 0; j < fields.FieldCount; j++) { if (fields.get_Field(j).Type == esriFieldType.esriFieldTypeGeometry) { strShapeField = fields.get_Field(j).Name; } } //create feature class in memory workspace pFC = pFeatureWorkspace.CreateFeatureClass(featureClassName, fields, pCLSID, null, esriFeatureType.esriFTSimple, strShapeField, null); return(pFC); }
// create feature class in file geodatabase #region "create feature class in file geodatabase" public static ESRI.ArcGIS.Geodatabase.IFeatureClass CreateFeatureClass(String featureClassName, UID classExtensionUID, IFeatureWorkspace featureWorkspace) { // check if the fc exist, if so rename it // Create a fields collection for the feature class. IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; // Add an object ID field to the fields collection. This is mandatory for feature classes. IField oidField = new FieldClass(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OBJECTID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); // Create a geometry definition (and spatial reference) for the feature class. IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_12N); ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Add a geometry field to the fields collection. This is where the geometry definition is applied. IField geometryField = new FieldClass(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); // Create a text field called "ADDRSYS_L" for the fields collection. IField addrSysLField = new FieldClass(); IFieldEdit addrSysLFieldEdit = (IFieldEdit)addrSysLField; addrSysLFieldEdit.Name_2 = "ADDRSYS_L"; addrSysLFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; addrSysLFieldEdit.Length_2 = 30; fieldsEdit.AddField(addrSysLField); // Create a text field called "ADDRSYS_R" for the fields collection. IField addrSysRField = new FieldClass(); IFieldEdit addrSysRFieldEdit = (IFieldEdit)addrSysRField; addrSysRFieldEdit.Name_2 = "ADDRSYS_R"; addrSysRFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; addrSysRFieldEdit.Length_2 = 30; fieldsEdit.AddField(addrSysRField); // Create a text field called "FROMADDR_L" for the fields collection. IField rangeL_Ffield = new FieldClass(); IFieldEdit rangeL_FfieldEdit = (IFieldEdit)rangeL_Ffield; rangeL_FfieldEdit.Name_2 = "FROMADDR_L"; rangeL_FfieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; rangeL_FfieldEdit.Precision_2 = 38; rangeL_FfieldEdit.Scale_2 = 8; fieldsEdit.AddField(rangeL_Ffield); // Create a text field called "TOADDR_L" for the fields collection. IField rangeL_Tfield = new FieldClass(); IFieldEdit rangeL_TfieldEdit = (IFieldEdit)rangeL_Tfield; rangeL_TfieldEdit.Name_2 = "TOADDR_L"; rangeL_TfieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; rangeL_TfieldEdit.Precision_2 = 38; rangeL_TfieldEdit.Scale_2 = 8; fieldsEdit.AddField(rangeL_Tfield); // Create a text field called "FROMADDR_R" for the fields collection. IField rangeR_Ffield = new FieldClass(); IFieldEdit rangeR_FfieldEdit = (IFieldEdit)rangeR_Ffield; rangeR_FfieldEdit.Name_2 = "FROMADDR_R"; rangeR_FfieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; rangeR_FfieldEdit.Precision_2 = 38; rangeR_FfieldEdit.Scale_2 = 8; fieldsEdit.AddField(rangeR_Ffield); // Create a text field called "TOADDR_R" for the fields collection. IField rangeR_Tfield = new FieldClass(); IFieldEdit rangeR_TfieldEdit = (IFieldEdit)rangeR_Tfield; rangeR_TfieldEdit.Name_2 = "TOADDR_R"; rangeR_TfieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; rangeR_TfieldEdit.Precision_2 = 38; rangeR_TfieldEdit.Scale_2 = 8; fieldsEdit.AddField(rangeR_Tfield); // Create a text field called "PREDIR" for the fields collection. IField predirField = new FieldClass(); IFieldEdit predirFieldEdit = (IFieldEdit)predirField; predirFieldEdit.Name_2 = "PREDIR"; predirFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; predirFieldEdit.Length_2 = 1; fieldsEdit.AddField(predirField); // Create a text field called "NAME" for the fields collection. IField nameField = new FieldClass(); IFieldEdit nameFieldEdit = (IFieldEdit)nameField; nameFieldEdit.Name_2 = "NAME"; nameFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; nameFieldEdit.Length_2 = 30; fieldsEdit.AddField(nameField); // Create a text field called "POSTTYPE" for the fields collection. IField streettypeField = new FieldClass(); IFieldEdit streettypeFieldEdit = (IFieldEdit)streettypeField; streettypeFieldEdit.Name_2 = "POSTTYPE"; streettypeFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; streettypeFieldEdit.Length_2 = 4; fieldsEdit.AddField(streettypeField); // Create a text field called "POSTDIR" for the fields collection. IField sufdirField = new FieldClass(); IFieldEdit sufdirFieldEdit = (IFieldEdit)sufdirField; sufdirFieldEdit.Name_2 = "POSTDIR"; sufdirFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; sufdirFieldEdit.Length_2 = 2; fieldsEdit.AddField(sufdirField); // Create a text field called "ZIPCODE_L" for the fields collection. IField zipleftField = new FieldClass(); IFieldEdit zipleftFieldEdit = (IFieldEdit)zipleftField; zipleftFieldEdit.Name_2 = "ZIPCODE_L"; zipleftFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; zipleftFieldEdit.Length_2 = 5; fieldsEdit.AddField(zipleftField); // Create a text field called "ZIPCODE_R" for the fields collection. IField ziprightField = new FieldClass(); IFieldEdit ziprightFieldEdit = (IFieldEdit)ziprightField; ziprightFieldEdit.Name_2 = "ZIPCODE_R"; ziprightFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; ziprightFieldEdit.Length_2 = 5; fieldsEdit.AddField(ziprightField); // Create a text field called "GLOBALID_SGID" for the fields collection - to join to the table or sgid. IField globalidField = new FieldClass(); IFieldEdit globalidFieldEdit = (IFieldEdit)globalidField; globalidFieldEdit.Name_2 = "GLOBALID_SGID"; globalidFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; // use string and not the globalid type b/c it might that might assign it's own unique global id and this is for joinging back to sgid globalidFieldEdit.Length_2 = 50; fieldsEdit.AddField(globalidField); // Use IFieldChecker to create a validated fields collection. IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = (IWorkspace)featureWorkspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); // The enumFieldError enumerator can be inspected at this point to determine // which fields were modified during validation. // Create the feature class. Note that the CLSID parameter is null - this indicates to use the // default CLSID, esriGeodatabase.Feature (acceptable in most cases for feature classes). IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, null, classExtensionUID, esriFeatureType.esriFTSimple, "Shape", ""); return(featureClass); }
private void OpenCADFile(string filePath, string outputFilePath) { try { Debug.WriteLine("Start Time: " + DateTime.Now.ToShortTimeString()); System.Windows.Forms.Cursor.Current = Cursors.WaitCursor; String nameOfPath = System.IO.Path.GetDirectoryName(filePath); String nameOfCADFile = System.IO.Path.GetFileName(filePath); #region Open CAD Workspace from File Path //Set the workspace. ESRI.ArcGIS.Geodatabase.IWorkspaceFactory pWorkspaceFact = new ESRI.ArcGIS.DataSourcesFile.CadWorkspaceFactory(); ESRI.ArcGIS.Geodatabase.IWorkspaceFactory defaultWorkspaceFact = new FileGDBWorkspaceFactory(); //Open the workspace. ESRI.ArcGIS.Geodatabase.IWorkspace pWorkspace = pWorkspaceFact.OpenFromFile(nameOfPath, 0); //Get the CADDrawingWorkspace. ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace pCadDwgWorkspace; pCadDwgWorkspace = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace)pWorkspace; //Open the CadDrawingDataset. ESRI.ArcGIS.DataSourcesFile.ICadDrawingDataset pCadDwgDataset; pCadDwgDataset = pCadDwgWorkspace.OpenCadDrawingDataset(nameOfCADFile); //Set the feature workspace. ESRI.ArcGIS.Geodatabase.IFeatureWorkspace pFeatureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)pWorkspace; //Open the Feature Class. #endregion #region Getting Polygon, polylines, and annotation from Cad file ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polygon")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Plyline = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polyline")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Anno = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Annotation")); #endregion UID CLSID_def = new UIDClass(); CLSID_def.Value = "esriGeoDatabase.Feature"; #region Creating Layers from Feature Classes //Polygons ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer.FeatureClass = pFeatClass; pFeatLayer.Name = "Polygons"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer; //Annotation ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Anno = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Anno.FeatureClass = pFeatClass_Anno; pFeatLayer_Anno.Name = "Annotation"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Anno = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Anno; //Polylines ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Plyline = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Plyline.FeatureClass = pFeatClass_Plyline; pFeatLayer_Plyline.Name = "Polylines"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Plyline = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Plyline; #endregion #region Creating In-Memory workspace IWorkspaceFactory WF = new InMemoryWorkspaceFactory(); ESRI.ArcGIS.esriSystem.IName name = WF.Create("", "MyWorkspace", null, 0) as ESRI.ArcGIS.esriSystem.IName; IWorkspace inMemWorkspace = (IWorkspace)name.Open(); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)inMemWorkspace; #endregion #region Creating new Fields IObjectClassDescription objectClassDescription = new FeatureClassDescription(); // create the fields using the required fields method IFields exportFields = new Fields(); IFieldsEdit fieldsEdit = (IFieldsEdit)exportFields; //OID IField field = new Field(); IField oidField = new Field(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); // Create a geometry definition (and spatial reference) for the feature class IGeometryDef geometryDef = new GeometryDef(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; IGeoDataset dataSet = (IGeoDataset)pFeatClass.FeatureDataset; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironment(); ISpatialReference spatialReference = dataSet.SpatialReference; ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Add a geometry field to the fields collection. This is where the geometry definition is applied. IField geometryField = new Field(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); #endregion #region Creating New Shapefile for Final output UID CLSID = new UIDClass(); CLSID.Value = "esriGeoDatabase.Feature"; //using the In-Memory Workspace created above IFeatureClass output = featureWorkspace.CreateFeatureClass("myPolygons", pFeatClass.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass polylines_cleaned = featureWorkspace.CreateFeatureClass("polylines_cleaned", pFeatClass_Plyline.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass annotation_cleaned = featureWorkspace.CreateFeatureClass("annotation_cleaned", pFeatClass_Anno.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); #endregion #region Appending features from CADWorkspaceFeatureClass to In-Memory FeatureClass Because Update cursor not in Cad workspace Geoprocessor GP = new Geoprocessor(); //Polylines ESRI.ArcGIS.DataManagementTools.Append append = new Append(); append.inputs = pFeatClass_Plyline; append.target = polylines_cleaned; GP.Execute(append, null); //System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Plyline); GC.Collect(); //Annotation append = new Append(); append.inputs = pFeatClass_Anno; append.target = annotation_cleaned; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Anno); GC.Collect(); //Polygons to output append = new Append(); append.inputs = pFeatClass; append.target = output; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass); GC.Collect(); #endregion #region Query Filter to Filter Layers string queryString = ""; //using the checked box list and comma seperated list to create where clause string //Adding Items from Check Box List foreach (var checkedItem in checkedListBox1.CheckedItems) { queryString = queryString + "Layer NOT LIKE '" + checkedItem.ToString() + "' AND "; } //Adding Items from Comma separated string if (textBox_commaSeparated.Text.Length > 0) { foreach (var item in textBox_commaSeparated.Text.Split(',')) { queryString = queryString + "Layer NOT LIKE '" + item.ToString() + "' AND "; } } //Removing Last 'AND' FROM queryString if (queryString.Length > 0) //if Atleast one item added { queryString = queryString.Remove(queryString.Length - 4); } IQueryFilter queryFilter = new QueryFilter(); queryFilter.SubFields = ""; if (queryString.Length > 0) { queryFilter.WhereClause = queryString; } else { queryFilter.WhereClause = "1=1"; } #endregion #region Removing Null Geometries string ignoreList = queryString.Replace("Layer NOT LIKE '", "").Replace("' AND ", ",").Replace("' ", ""); Debug.WriteLine("lines Count before:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From Polylines_cleaned IFeatureCursor updateCursor = polylines_cleaned.Update(new QueryFilter(), false); IFeature feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); //System.Runtime.InteropServices.Marshal.ReleaseComObject(feat); GC.Collect(); Debug.WriteLine("lines Count After:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From output Debug.WriteLine("polygons Count before:" + output.FeatureCount(new QueryFilter()).ToString()); updateCursor = output.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("polygons Count after:" + output.FeatureCount(new QueryFilter()).ToString()); //From Annotation Debug.WriteLine("Annotation Count before:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); updateCursor = annotation_cleaned.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("Annotation Count after:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); #endregion #region Convert lines feature class to feature Cursor IFeatureCursor linesFCursor = polylines_cleaned.Search(new QueryFilter(), false); #endregion #region Deleting all columns of polygons to match with output IFields _fieldsP = output.Fields; IFieldsEdit _fieldsEditP = (IFieldsEdit)_fieldsP; for (int i = 0; i < output.Fields.FieldCount; i++) { IField _field = output.Fields.get_Field(i); if (_field.Name != "Shape" && _field.Name != "FID") { output.DeleteField(_field); if (i < output.Fields.FieldCount) { i--; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsP); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEditP); GC.Collect(); #endregion #region Setting Envelop information IEnvelope envelop = new Envelope() as IEnvelope; IGeoDataset dataSetEnv = (IGeoDataset)pFeatClass_Plyline.FeatureDataset; envelop.SpatialReference = dataSet.SpatialReference; envelop.PutCoords(dataSet.Extent.XMin, dataSet.Extent.YMin, dataSet.Extent.XMax, dataSet.Extent.YMax); #endregion #region Construct Polygons from Lines Cursor (usting Feature Construct) IFeatureConstruction featureConstruct = new FeatureConstruction() as IFeatureConstruction; ISelectionSet selectionSet = null; //atureConstruct.ConstructPolygonsFromFeaturesFromCursor(null,output,envelop,false,false,linesFCursor,null,0.001,null); featureConstruct.AutoCompleteFromFeaturesFromCursor(output, envelop, linesFCursor, null, -1, null, out selectionSet); #endregion System.Runtime.InteropServices.Marshal.ReleaseComObject(featureConstruct); System.Runtime.InteropServices.Marshal.ReleaseComObject(linesFCursor); GC.Collect(); Debug.WriteLine("polygons Count after PolygonConstruct :" + output.FeatureCount(new QueryFilter()).ToString()); #region SPATIAL JOIN GP = new Geoprocessor(); ESRI.ArcGIS.AnalysisTools.SpatialJoin spatialJoin = new ESRI.ArcGIS.AnalysisTools.SpatialJoin(); spatialJoin.join_features = annotation_cleaned; spatialJoin.target_features = output; spatialJoin.join_operation = "JOIN_ONE_TO_MANY"; spatialJoin.join_type = "KEEP_ALL"; spatialJoin.match_option = "CONTAINS"; spatialJoin.out_feature_class = outputFilePath; GP.Execute(spatialJoin, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(annotation_cleaned); GC.Collect(); #endregion #region Remove All Fields of Annotation except Text ShapefileWorkspaceFactory wsf = new ShapefileWorkspaceFactory(); IFeatureWorkspace work = (IFeatureWorkspace)wsf.OpenFromFile(System.IO.Path.GetDirectoryName(outputFilePath), 0); IFeatureClass output_AfterJoin_FClasss = work.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(outputFilePath)); IFields _fields = output_AfterJoin_FClasss.Fields; IFieldsEdit _fieldsEdit = (IFieldsEdit)_fields; for (int i = 0; i < _fields.FieldCount; i++) { IField _field = output_AfterJoin_FClasss.Fields.get_Field(i); if (_field.Name != "Text_" && _field.Name != "Text" && _field.Name != "Shape" && _field.Name != "FID") { output_AfterJoin_FClasss.DeleteField(_field); i--; } else { if (field.Name == "Text_" || _field.Name == "Text") { IFieldEdit fieldEdit = (IFieldEdit)_field; fieldEdit.Name_2 = "PlotNumber"; fieldEdit.AliasName_2 = "PlotNumber"; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fields); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEdit); GC.Collect(); #endregion System.Windows.Forms.Cursor.Current = Cursors.Default; Debug.WriteLine("End Time: " + DateTime.Now.ToShortTimeString()); MessageBox.Show("Import Complete!"); } catch { MessageBox.Show("Error Importing. Something wrong with the CAD File"); } }
//创建featureclass private IFeatureClass CreateFeatureClass(string name, IWorkspace pWorkspace, UID uidCLSID, UID uidCLSEXT, IGeometry pGeometry) { try { if (uidCLSID == null) { uidCLSID = new UIDClass(); uidCLSID.Value = "{52353152-891A-11D0-BEC6-00805F7C4268}"; } // 设置 uidCLSEXT (if Null) //uidCLSEXT == null; IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace; IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; IField oidField = new FieldClass(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = pGeometry.GeometryType; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = pGeometry.SpatialReference; ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; IField geometryField = new FieldClass(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); // Use IFieldChecker to create a validated fields collection. IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = pWorkspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); IFeatureClass targetFeatureclass = null; targetFeatureclass = pFeatureWorkspace.CreateFeatureClass("" + name + "", fields, uidCLSID, uidCLSEXT, esriFeatureType.esriFTSimple, "Shape", ""); return(targetFeatureclass); } catch (Exception ex) { if (ex.Message == "Cannot create a low precision dataset in a high precision database.") { MessageBox.Show("数据必须是ArcGis9.3的数据,请将数据处理成ArcGis9.2的数据!"); } } IFeatureClass featureclass = null; return(featureclass); }
/// <summary> /// 创建一个要素集 /// </summary> private void CreateFeatureClass() { string path = txt_org.Text; string PRJFile = txt_prj.Text; AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWorkspace = pAccessFact.OpenFromFile(path, 0) as IFeatureWorkspace; ISpatialReferenceFactory2 Isp = new SpatialReferenceEnvironmentClass(); //创建一个空间参照的接口空间 ISpatialReference spatial = Isp.CreateESRISpatialReferenceFromPRJFile(PRJFile); //利用要素类的PRJ文件参照 ISpatialReferenceResolution pSRR = (ISpatialReferenceResolution)spatial; //设置分辨率 pSRR.SetDefaultXYResolution(); //设置默认XY值 ISpatialReferenceTolerance pSRT = (ISpatialReferenceTolerance)spatial; pSRT.SetDefaultXYTolerance();//设置默认容差值 IWorkspace space = pFeatureWorkspace as IWorkspace; IEnumDatasetName Dataset_name = space.get_DatasetNames(esriDatasetType.esriDTAny);//得到有多少个要素集合名字 Dataset_name.Reset(); IDatasetName Name_set = Dataset_name.Next(); while (Name_set != null) { if (Name_set.Name == "Geo_Topo_ice") { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "数据集已存在,不用创建!"); this.Close();//如果要创建的数据集已存在,就返回,并关闭窗体 return; } Name_set = Dataset_name.Next(); } IFeatureDataset pfd = pFeatureWorkspace.CreateFeatureDataset("Geo_Topo_ice", spatial); //创建一个要素集 IEnumDataset dst = space.get_Datasets(esriDatasetType.esriDTAny); //得到所有的要素类的一个集合 dst.Reset(); IDataset det = dst.Next(); _AppHk.OperatorTips = "开始创建对应的要素类..."; while (det != null) { #region 给要素集创建空的要素类 if (det.Type == esriDatasetType.esriDTFeatureClass) //判定是不是要素类 { string org_name = det.Name; //原始的名字 _AppHk.OperatorTips = "开始创建" + org_name + "要素类..."; IFeatureClass f_class = pFeatureWorkspace.OpenFeatureClass(org_name); //打开源要素类 det.Rename(org_name + "_t"); //把源要素类进行重命名 IFields Fieldset = new FieldsClass(); //建立一个字段集 IFieldsEdit sField = Fieldset as IFieldsEdit; //字段集 if (f_class.FeatureType != esriFeatureType.esriFTAnnotation) { //shape IGeometryDefEdit d_edit; //定义一个用来接收要素类的SHAPE类型 d_edit = new GeometryDefClass(); //实例一个操作类 d_edit.GeometryType_2 = f_class.ShapeType; //将源要素类的SHAPE赋值给我们要创建的几何类型 d_edit.SpatialReference_2 = spatial; //空间参考 string OID = f_class.OIDFieldName; //ODI名字 string SHAPE = f_class.ShapeFieldName; //SHAPE名字 //IFields Fieldset = new FieldsClass();//建立一个字段集 //IFieldsEdit sField = Fieldset as IFieldsEdit;//字段集 //创建要素类里的字段 int count = f_class.Fields.FieldCount;//确定有多少个字段 #region 创建字段 for (int n = 0; n < count; n++) { IField f_ield = f_class.Fields.get_Field(n); IFieldEdit fieldEdit = f_ield as IFieldEdit; //Annotate if (f_ield.Name == SHAPE) { //shape field fieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; //确定字段的类型 fieldEdit.GeometryDef_2 = d_edit; //把几何类型赋值给它 fieldEdit.Name_2 = SHAPE; //把几何类型SHPAE的名字赋值给它 f_ield = fieldEdit as IField; sField.AddField(f_ield); //加入要素集 } else if (f_ield.Name == OID) { //oid fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; //OID标识字段 fieldEdit.Name_2 = OID; //OID的名字 f_ield = fieldEdit as IField; sField.AddField(f_ield); //加入OID } else { //一般字段 fieldEdit.Name_2 = f_ield.Name; fieldEdit.Type_2 = f_ield.Type;//字段的类型 f_ield = fieldEdit as IField; sField.AddField(f_ield); } } #endregion Fieldset = sField as IFields; //将可编辑的字段集转成一般字段集 pfd.CreateFeatureClass(org_name, Fieldset, f_class.CLSID, null, esriFeatureType.esriFTSimple, SHAPE, ""); //给要素集中创建要素类 } else { createAnnoFeatureClass(org_name, pfd, pfd.Workspace as IFeatureWorkspace, sField, 2000); } det = dst.Next();//重新遍历下一个 } else { det = dst.Next();//重新遍历下一个 } #endregion } _AppHk.OperatorTips = "要素集合创建成功!"; GetValue(pFeatureWorkspace);//当对应的要素类建立好后,就开始给空要素类赋值 SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "数据处理完成!"); this.Close(); }