public static IFields CreateFields(esriGeometryType geoType) { IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; IFields fields = ocDescription.RequiredFields; int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = geoType; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); var sr = spatialReferenceFactory.CreateGeographicCoordinateSystem(4326); geometryDefEdit.SpatialReference_2 = sr; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; field = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Name"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.AddField(field); return(fields); }
/// <summary> /// 创建一个要素集 /// </summary> /// <param name="shpfolder"></param> /// <param name="shpname"></param> /// <returns></returns> public static IFeatureClass CreatePolygonFeatureClass(string shpfolder, string shpname) { IWorkspaceFactory pWorkSpaceFac = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWorkSpace = pWorkSpaceFac.OpenFromFile(shpfolder, 0) as IFeatureWorkspace; //创建字段集2 IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;//创建必要字段 IFields fields = ocDescription.RequiredFields; int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; //geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; //geometryDefEdit.SpatialReference_2 = spatialReference; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass(); IProjectedCoordinateSystem pcsSys = pSpatialRefFac.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_Zone_39); geometryDefEdit.SpatialReference_2 = pcsSys; IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; //将传入字段 转成 validatedFields fieldChecker.ValidateWorkspace = (IWorkspace)pFeatureWorkSpace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); IFeatureClass featureClass = pFeatureWorkSpace.CreateFeatureClass(shpname, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); AddField(featureClass, "BuildID", "自带id", 50); return(featureClass); }
public IFeatureClass CreateFeatureClass(string geometryType) { IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetTempPath(), 0); IFeatureClass featureClass; IFields fields; UID CLSID = new UIDClass(); CLSID.Value = "esriGeoDatabase.Feature"; IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass(); // create the fields using the required fields method fields = objectClassDescription.RequiredFields; string strShapeField = ""; // locate the shape field for (int j = 0; j < fields.FieldCount; j++) { if (fields.get_Field(j).Type == ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeGeometry) { strShapeField = fields.get_Field(j).Name; } } featureClass = featureWorkspace.CreateFeatureClass(tempFeatureLayerName, fields, CLSID, null, esriFeatureType.esriFTSimple, strShapeField, null); return(featureClass); }
// //create fields needed in roi shp file // private static IFields CreateFields(string xzqmc, string layer) { IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass(); IFields requiredFields = objectClassDescription.RequiredFields; IFieldsEdit fieldsEdit = requiredFields as IFieldsEdit; IField field1 = new FieldClass(); IFieldEdit fieldEdit1 = field1 as IFieldEdit; fieldEdit1.Name_2 = _YFBH; fieldEdit1.Type_2 = esriFieldType.esriFieldTypeInteger; IField field2 = new FieldClass(); IFieldEdit fieldEdit2 = field2 as IFieldEdit; fieldEdit2.Name_2 = xzqmc; fieldEdit2.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit2.Length_2 = 50; IField field3 = new FieldClass(); IFieldEdit fieldEdit3 = field3 as IFieldEdit; fieldEdit3.Name_2 = layer; fieldEdit3.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field1); fieldsEdit.AddField(field2); fieldsEdit.AddField(field3); return(requiredFields); }
public static IFeatureClass CreateFeatureClass(IWorkspace workspace, string featureClassName, esriGeometryType type, ISpatialReference spatialReference) { IFeatureWorkspace pFeatureWorkspace = workspace as IFeatureWorkspace; IFeatureClassDescription pFeatureClassDescription = new FeatureClassDescriptionClass(); IObjectClassDescription pObjectClassDescription = pFeatureClassDescription as IObjectClassDescription; IFields pFields = pObjectClassDescription.RequiredFields; IFieldsEdit pFieldsEdit = pFields as IFieldsEdit; for (int i = 0; i < pFields.FieldCount; i++) { if (pFieldsEdit.Field[i].Type == esriFieldType.esriFieldTypeGeometry) { IFieldEdit pFieldEdit = pFieldsEdit.Field[i] as IFieldEdit; IGeometryDef pGeometryDef = new GeometryDefClass(); IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit; pGeometryDefEdit.GeometryType_2 = type; pGeometryDefEdit.SpatialReference_2 = spatialReference; pFieldEdit.GeometryDef_2 = pGeometryDef; } } IFieldChecker pFieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; pFieldChecker.ValidateWorkspace = workspace; pFieldChecker.Validate(pFields, out enumFieldError, out validatedFields); return(pFeatureWorkspace.CreateFeatureClass(featureClassName, validatedFields, pObjectClassDescription.InstanceCLSID, pObjectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "SHAPE", "")); }
private static IFeatureClass CreateFeaturepointClass(String featureClassName, IFeatureWorkspace featureWorkspace, ISpatialReference spatialReference) { try { IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; IFields fields = ocDescription.RequiredFields; int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; geometryDefEdit.SpatialReference_2 = spatialReference; IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, fields, ocDescription.ClassExtensionCLSID, ocDescription.InstanceCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); return(featureClass); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "异常"); return(null); } }
private void button1_Click(object sender, EventArgs e) { try { if (!String.IsNullOrEmpty(textBox1.Text) && !String.IsNullOrEmpty(textBox2.Text)) { string databasefilename = openFileDialog1.FileName; IWorkspace workspace = AccessWorkspaceFromPropertySet(databasefilename); ISpatialReference spatialreference = map.SpatialReference; IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc; IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IFeatureWorkspace featureworkspace = (IFeatureWorkspace)workspace; IFeatureClass featureclass = CreateFeatureClass(textBox1.Text, featureworkspace); if (featureclass == null) { MessageBox.Show("Feature Class not created"); } else { MessageBox.Show("Feature Class successfull created"); } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } textBox1.Clear(); textBox2.Clear(); panel3.Visible = false; }
// //create fields needed in roi shp file // private IFields CreateFields() { IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass(); IFields requiredFields = objectClassDescription.RequiredFields; IFieldsEdit fieldsEdit = requiredFields as IFieldsEdit; IField field1 = new FieldClass(); IFieldEdit fieldEdit1 = field1 as IFieldEdit; fieldEdit1.Name_2 = "CLASS_NAME"; fieldEdit1.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit1.Length_2 = 50; IField field2 = new FieldClass(); IFieldEdit fieldEdit2 = field2 as IFieldEdit; fieldEdit2.Name_2 = "CLASS_ID"; fieldEdit2.Type_2 = esriFieldType.esriFieldTypeInteger; IField field3 = new FieldClass(); IFieldEdit fieldEdit3 = field3 as IFieldEdit; fieldEdit3.Name_2 = "CLASS_CLRS"; fieldEdit3.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit3.Length_2 = 50; fieldsEdit.AddField(field1); fieldsEdit.AddField(field2); fieldsEdit.AddField(field3); return(requiredFields); }
private IFeatureClass CreateFeatureClass(IFeatureWorkspace FeatureWorkspace, string LayerName, esriFeatureType featureType, esriGeometryType GeometryType) { IFields fields = new FieldsClass(); IFieldsEdit edit = fields as IFieldsEdit; //创建OBJECTID字段 IField field3 = new FieldClass(); IFieldEdit edit2 = field3 as IFieldEdit; edit2.Name_2 = "OBJECTID"; edit2.AliasName_2 = "OBJECTID"; edit2.Type_2 = esriFieldType.esriFieldTypeOID; edit.AddField(field3); //创建Shape字段 IGeometryDef def = new GeometryDefClass(); IGeometryDefEdit edit4 = def as IGeometryDefEdit; edit4.GeometryType_2 = GeometryType; edit4.GridCount_2 = 1; edit4.set_GridSize(0, 1000); edit4.AvgNumPoints_2 = 2; edit4.HasM_2 = false; edit4.HasZ_2 = false; edit4.SpatialReference_2 = this.ExportSpatialReference; IField field4 = new FieldClass(); IFieldEdit edit3 = field4 as IFieldEdit; edit3.Name_2 = "SHAPE"; edit3.AliasName_2 = "SHAPE"; edit3.Type_2 = esriFieldType.esriFieldTypeGeometry; edit3.GeometryDef_2 = def; edit.AddField(field4); string ShapeFiledName = field4.Name; UID uid = null; UID uid2 = null; switch (featureType) { case esriFeatureType.esriFTSimple: //FeatureClass IObjectClassDescription description4 = new FeatureClassDescriptionClass(); uid = description4.InstanceCLSID; uid2 = description4.ClassExtensionCLSID; break; case esriFeatureType.esriFTAnnotation: //AnnotationFeatureClass IObjectClassDescription description = new AnnotationFeatureClassDescriptionClass(); uid = description.InstanceCLSID; uid2 = description.ClassExtensionCLSID; GeometryType = esriGeometryType.esriGeometryPolygon; break; } //创建要素对象 IFeatureClass fc = FeatureWorkspace.CreateFeatureClass(LayerName, fields, uid, uid2, featureType, ShapeFiledName, null); return(fc); }
private bool RemoveClsExt(IClass classExtension) { ISchemaLock schemaLock = (ISchemaLock)classExtension; bool result = false; try { // Attempt to get an exclusive schema lock. schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock); // Cast the object class to the IClassSchemaEdit2 interface. IClassSchemaEdit2 classSchemaEdit = (IClassSchemaEdit2)classExtension; // Clear the class extension. classSchemaEdit.AlterClassExtensionCLSID(null, null); IObjectClassDescription featureClassDescription = new FeatureClassDescriptionClass(); classSchemaEdit.AlterInstanceCLSID(featureClassDescription.InstanceCLSID); result = true; } catch { result = false; } finally { schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); } return(result); }
private string GenerateTemp3DPolygonStorage() { string newFeatureClassName = $"Polygon3D_L{Helper.GetTemporaryNameSuffix()}"; IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; IFields fields = ocDescription.RequiredFields; int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.HasZ_2 = true; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; geometryDefEdit.SpatialReference_2 = ArcMapInstance.Document.FocusMap.SpatialReference; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; IField isVisibleField = new FieldClass(); IFieldEdit isVisibleFieldEdit = (IFieldEdit)isVisibleField; isVisibleFieldEdit.Name_2 = "IS_VISIBLE"; isVisibleFieldEdit.Type_2 = esriFieldType.esriFieldTypeSmallInteger; fieldsEdit.AddField(isVisibleFieldEdit); GenerateTempStorage(newFeatureClassName, fields, esriGeometryType.esriGeometryPolygon); return(newFeatureClassName); }
/// <summary> /// create feature class of output /// </summary> /// <param name="workspace">object workspace</param> /// <param name="spatialReference">spatial reference of feature class of output</param> /// <param name="nameFeatureClass">name of feature class</param> /// <returns>object feature class</returns> private static IFeatureClass CreateFeatureClassOutput(IWorkspace workspace, ISpatialReference spatialReference, string nameFeatureClass) { IFeatureClassDescription featureClassDescription = new FeatureClassDescriptionClass(); IObjectClassDescription objectClassDescription = (IObjectClassDescription)featureClassDescription; IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace; // Create the fields collection. IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; IField oidField = new FieldClass(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OBJECTID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); // Create the Shape field. IField shapeField = new Field(); IFieldEdit shapeFieldEdit = (IFieldEdit)shapeField; // Set up the geometry definition for the Shape field. IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; // By setting the grid size to 0, you're allowing ArcGIS to determine the appropriate grid sizes for the feature class. // If in a personal geodatabase, the grid size will be 1000. If in a file or ArcSDE geodatabase, the grid size // will be based on the initial loading or inserting of features. geometryDefEdit.HasM_2 = false; geometryDefEdit.HasZ_2 = false; geometryDefEdit.SpatialReference_2 = spatialReference; // Set standard field properties. shapeFieldEdit.Name_2 = featureClassDescription.ShapeFieldName; shapeFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; shapeFieldEdit.GeometryDef_2 = geometryDef; shapeFieldEdit.IsNullable_2 = true; shapeFieldEdit.Required_2 = true; fieldsEdit.AddField(shapeField); IField idField = new FieldClass(); IFieldEdit idIsolaFieldEdit = (IFieldEdit)idField; idIsolaFieldEdit.Name_2 = Program.nameFieldIdOutput; idIsolaFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(idField); // Use IFieldChecker to create a validated fields collection. IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = workspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); return featureWorkspace.CreateFeatureClass(nameFeatureClass, fields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, featureClassDescription.ShapeFieldName, string.Empty); }
public void InitFields() { IFields requiredFields; if (this.IsFeatureClass) { IFeatureClassDescription description; IGeometryDef geometryDef; if (this.FeatureType == esriFeatureType.esriFTSimple) { description = new FeatureClassDescriptionClass(); requiredFields = (description as IObjectClassDescription).RequiredFields; this.ifield_0 = requiredFields.get_Field(requiredFields.FindField(description.ShapeFieldName)); geometryDef = (this.ifield_0 as IFieldEdit2).GeometryDef; (geometryDef as IGeometryDefEdit).GeometryType_2 = m_pObjectClassHelper.ShapeType; if (this.ispatialReference_0 != null) { (geometryDef as IGeometryDefEdit).SpatialReference_2 = this.ispatialReference_0; } (geometryDef as IGeometryDefEdit).HasZ_2 = this.bool_3; (geometryDef as IGeometryDefEdit).HasM_2 = this.bool_4; (this.ifield_0 as IFieldEdit).GeometryDef_2 = geometryDef as IGeometryDefEdit; this.ifields_0 = requiredFields; } else if (this.FeatureType == esriFeatureType.esriFTAnnotation) { description = new AnnotationFeatureClassDescriptionClass(); requiredFields = (description as IObjectClassDescription).RequiredFields; this.ifield_0 = requiredFields.get_Field(requiredFields.FindField(description.ShapeFieldName)); geometryDef = (this.ifield_0 as IFieldEdit2).GeometryDef; if (this.ispatialReference_0 != null) { (geometryDef as IGeometryDefEdit).SpatialReference_2 = this.ispatialReference_0; } this.ifields_0 = requiredFields; } else if (this.FeatureType == esriFeatureType.esriFTDimension) { description = new DimensionClassDescriptionClass(); requiredFields = (description as IObjectClassDescription).RequiredFields; this.ifield_0 = requiredFields.get_Field(requiredFields.FindField(description.ShapeFieldName)); geometryDef = (this.ifield_0 as IFieldEdit2).GeometryDef; if (this.ispatialReference_0 != null) { (geometryDef as IGeometryDefEdit).SpatialReference_2 = this.ispatialReference_0; } this.ifields_0 = requiredFields; } } else { IObjectClassDescription description2 = new FeatureClassDescriptionClass(); requiredFields = description2.RequiredFields; this.ifields_0 = requiredFields; } }
/// <summary> /// create a feature class in workspace with type geometry /// </summary> /// <param name="geometry">geometry of feature class</param> /// <param name="featureWorkspace">workspace for store feature class</param> /// <returns>feature class created</returns> private IFeatureClass CreateFeatureClass(IGeometry geometry, IFeatureWorkspace featureWorkspace) { // 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 = "OID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); IField idField = new FieldClass(); IFieldEdit idFieldEdit = (IFieldEdit)idField; idFieldEdit.Name_2 = SAUtility.FieldNameIdWatershed; idFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(idField); // Create a geometry definition (and spatial reference) for the feature class. IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = geometry.GeometryType; geometryDefEdit.SpatialReference_2 = geometry.SpatialReference; IFeatureClassDescription featureClassDescription = new FeatureClassDescriptionClass(); IObjectClassDescription objectClassDescription = (IObjectClassDescription)featureClassDescription; // 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 = featureClassDescription.ShapeFieldName; 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 = (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("pourPoint", validatedFields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, featureClassDescription.ShapeFieldName, string.Empty); return(featureClass); }
//字段集 private IFields CreateFieldsCollectionForFeatueClass(ISpatialReference spatialReference, esriGeometryType geometryType, string className) { //Use the feature class description to return the required fields in a fields collection. IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc; //Create the fields using the required fields method. IFields fields = ocDesc.RequiredFields; //Locate the shape field with the name from the feature class description. int shapeFieldIndex = fields.FindField(fcDesc.ShapeFieldName); IField shapeField = fields.get_Field(shapeFieldIndex); //Modify the GeometryDef object before using the fields collection to create a //feature class. IGeometryDef geometryDef = shapeField.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; //Alter the feature class geometry type to the type we need. geometryDefEdit.GeometryType_2 = geometryType; geometryDefEdit.HasZ_2 = true; geometryDefEdit.HasM_2 = true; geometryDefEdit.GridCount_2 = 1; //Set the first grid size to zero and allow ArcGIS to determine a valid grid size. geometryDefEdit.set_GridSize(0, 0); geometryDefEdit.SpatialReference_2 = spatialReference; //添加地质属性概率字段 if (geometryType == esriGeometryType.esriGeometryPoint) { //Create a user-defined double field for "probability" IFieldsEdit fieldsEdit = (IFieldsEdit)fields; IField incomeField = new FieldClass(); IFieldEdit incomeFieldEdit = (IFieldEdit)incomeField; incomeFieldEdit.AliasName_2 = "probability"; incomeFieldEdit.Editable_2 = true; incomeFieldEdit.IsNullable_2 = false; incomeFieldEdit.Name_2 = "probability"; incomeFieldEdit.Precision_2 = 2; incomeFieldEdit.Scale_2 = 5; incomeFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(incomeField); //Create a user-defined double field for "RegardP" IFieldsEdit fieldsEdit1 = (IFieldsEdit)fields; IField incomeField1 = new FieldClass(); IFieldEdit incomeFieldEdit1 = (IFieldEdit)incomeField1; incomeFieldEdit1.AliasName_2 = "RegardP"; incomeFieldEdit1.Editable_2 = true; incomeFieldEdit1.IsNullable_2 = false; incomeFieldEdit1.Name_2 = "RegardP"; incomeFieldEdit1.Precision_2 = 2; incomeFieldEdit1.Scale_2 = 5; incomeFieldEdit1.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit1.AddField(incomeField1); } return(fields); }
private void button2_Click(object sender, EventArgs e) { //工作空间 IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWorkspace = pWorkspaceFactory.OpenFromFile(pFilePath, 0) as IFeatureWorkspace; //创建字段集2 IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); //创建必要字段 IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; //必要字段 IFields pFields = new FieldsClass(); pFields = ocDescription.RequiredFields; //要素类的几何类型、坐标系 int shapeFileIndex = pFields.FindField(fcDescription.ShapeFieldName); IField pField = pFields.get_Field(shapeFileIndex); IGeometryDef pGeometryDef = pField.GeometryDef; IGeometryDefEdit pGeometryDefEdit = (IGeometryDefEdit)pGeometryDef; pGeometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironmentClass(); //更改为可选的坐标系 IProjectedCoordinateSystem pProjectedCoordinateSystem = pSpatialReferenceFactory.CreateProjectedCoordinateSystem( (int)esriSRProjCS4Type.esriSRProjCS_Xian1980_GK_Zone_21); pGeometryDefEdit.SpatialReference_2 = pProjectedCoordinateSystem; //自定义字段 IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields; addField(pFieldsEdit, "FID"); addField(pFieldsEdit, "Row"); addField(pFieldsEdit, "Column"); addField(pFieldsEdit, "Number"); //传入字段 IFieldChecker pFieldChecker = new FieldCheckerClass(); IEnumFieldError pEnumFieldError = null; IFields validatedFields = null; pFieldChecker.ValidateWorkspace = (IWorkspace)pFeatureWorkspace; pFieldChecker.Validate(pFields, out pEnumFieldError, out validatedFields); //创建要素类 IFeatureClass pFeatureClass = pFeatureWorkspace.CreateFeatureClass(pFileName, validatedFields , ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); MessageBox.Show("创建要素类成功"); }
/// <summary> /// 将Shapefile导入到数据库 /// </summary> /// <param name="pFeaClass"></param> /// <param name="pWorkspace"></param> /// <param name="tFeatureClass"></param> private void importToDB(IFeatureClass pFeaClass, IWorkspace pWorkspace, IFeatureDataset tFeatureClass, string SHPName) { IFeatureClassDescription featureClassDescription = new FeatureClassDescriptionClass(); IObjectClassDescription objectClassDescription = featureClassDescription as IObjectClassDescription; IFields pFields = pFeaClass.Fields; IFieldChecker pFieldChecker = new FieldCheckerClass(); IEnumFieldError pEnumFieldError = null; IFields vFields = null; pFieldChecker.ValidateWorkspace = pWorkspace as IWorkspace; pFieldChecker.Validate(pFields, out pEnumFieldError, out vFields); IFeatureWorkspace featureWorkspace = pWorkspace as IFeatureWorkspace; IFeatureClass sdeFeatureClass = null; if (sdeFeatureClass == null) { sdeFeatureClass = tFeatureClass.CreateFeatureClass(SHPName, vFields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, pFeaClass.FeatureType, pFeaClass.ShapeFieldName, ""); IFeatureCursor featureCursor = pFeaClass.Search(null, true); IFeature feature = featureCursor.NextFeature(); IFeatureCursor sdeFeatureCursor = sdeFeatureClass.Insert(true); IFeatureBuffer sdeFeatureBuffer; while (feature != null) { sdeFeatureBuffer = sdeFeatureClass.CreateFeatureBuffer(); IField shpField = new FieldClass(); IFields shpFields = feature.Fields; for (int i = 0; i < shpFields.FieldCount; i++) { shpField = shpFields.get_Field(i); if (shpField.Name.Contains("Area") || shpField.Name.Contains("Leng") || shpField.Name.Contains("FID")) { continue; } int index = sdeFeatureBuffer.Fields.FindField(shpField.Name); if (index != -1) { sdeFeatureBuffer.set_Value(index, feature.get_Value(i)); } } sdeFeatureCursor.InsertFeature(sdeFeatureBuffer); sdeFeatureCursor.Flush(); feature = featureCursor.NextFeature(); } featureCursor.Flush(); Marshal.ReleaseComObject(feature); Marshal.ReleaseComObject(featureCursor); } }
/// <summary> /// 创建指定名称的FeatureClass 适用于创建Stops和Barriers /// </summary> /// <param name="workspace"></param> /// <param name="name"></param> /// <param name="spatialReference">与主窗体上的axMapcontrol的连接吧...</param> public static IFeatureClass CreateFeatureClass(IFeatureWorkspace workspace, string name, ISpatialReference spatialReference = null) { if (spatialReference == null) { spatialReference = ApplicationV.GlobalMapControl.ActiveView.FocusMap.SpatialReference; } //创建字段集 IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; //创建字段组 IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields; IField Field_OID = new FieldClass(); IFieldEdit Field_OID_EDIT = Field_OID as IFieldEdit; Field_OID_EDIT.Name_2 = "OBJECTID"; Field_OID_EDIT.Type_2 = esriFieldType.esriFieldTypeOID; Field_OID_EDIT.IsNullable_2 = false; Field_OID_EDIT.Required_2 = false; pFieldsEdit.AddField(Field_OID); //创建一个必要的东西 IGeometryDef geoDef = new GeometryDefClass(); IGeometryDefEdit geoDefEdit = (IGeometryDefEdit)geoDef; geoDefEdit.AvgNumPoints_2 = 5; geoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; geoDefEdit.GridCount_2 = 1; geoDefEdit.HasM_2 = false; geoDefEdit.HasZ_2 = false; geoDefEdit.SpatialReference_2 = spatialReference; //创建SHAPE字段 IField Field_SHAPE = new FieldClass(); IFieldEdit pFieldEdit_SHAPE = (IFieldEdit)Field_SHAPE; pFieldEdit_SHAPE.Name_2 = "SHAPE"; pFieldEdit_SHAPE.Type_2 = esriFieldType.esriFieldTypeGeometry; pFieldEdit_SHAPE.GeometryDef_2 = geoDef; //放入组 pFieldsEdit.AddField(Field_SHAPE); //正式创建要素类 return(workspace.CreateFeatureClass(name, pFields, ocDescription.ClassExtensionCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, "")); }
/// <summary> /// 创建要素类 /// </summary> /// <param name="featureWorkspace"></param> /// <param name="name"></param> /// <param name="esriGeometryType"></param> /// <param name="fielddict"></param> /// <returns></returns> public static IFeatureClass CreateFeatureClass(IFeatureWorkspace featureWorkspace, string name, esriGeometryType esriGeometryType, Dictionary <string, GISField> fielddict) { IFields fields = new FieldsClass(); IFieldsEdit fieldsedit = fields as IFieldsEdit; IField field = new FieldClass(); IFieldEdit fieldedit = field as IFieldEdit; fieldedit.Name_2 = "shape"; fieldedit.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit pGeometryDefEdit = geometryDef as IGeometryDefEdit; pGeometryDefEdit.GeometryType_2 = esriGeometryType; ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference pSpatialReference = pSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); pSpatialReference.SetDomain(-6000000, 6000000, -6000000, 6000000); pGeometryDefEdit.SpatialReference_2 = pSpatialReference; fieldedit.GeometryDef_2 = geometryDef; fieldsedit.AddField(field); field = new FieldClass(); fieldedit = field as IFieldEdit; fieldedit.Name_2 = "FID"; fieldedit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsedit.AddField(field); foreach (var entry in fielddict) { if (entry.Key.ToUpper() == "SHAPE" || entry.Key.ToUpper() == "OBJECTID") { continue; } field = new FieldClass(); fieldedit = field as IFieldEdit; fieldedit.Name_2 = entry.Key; fieldedit.Type_2 = entry.Value.Type; fieldsedit.AddField(field); } IFeatureClassDescription featureClassDescription = new FeatureClassDescriptionClass(); IObjectClassDescription objectClassDescription = featureClassDescription as IObjectClassDescription; IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(name, fields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "shape", ""); return(featureClass); }
/// <summary> /// Create geometry layer /// </summary> /// <param name="sName">filename without extension</param> /// <param name="geometry">based geometry</param> /// <param name="featureWorkspace">featureWorkspace</param> /// <param name="sAlias"></param> /// <returns></returns> public static bool CreateGeometryLayer(string sName, List <ROIGeometry> geometryList, IFeatureWorkspace featureWorkspace, string sAlias = "") { bool result; try { IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass(); IFields requiredFields = objectClassDescription.RequiredFields; string shapeFieldName = (objectClassDescription as IFeatureClassDescription).ShapeFieldName; int index = requiredFields.FindField(shapeFieldName); IGeometryDef geometryDef = requiredFields.get_Field(index).GeometryDef; IGeometryDefEdit geometryDefEdit = geometryDef as IGeometryDefEdit; geometryDefEdit.GeometryType_2 = geometryList[0].geometry.GeometryType; geometryDefEdit.SpatialReference_2 = geometryList[0].geometry.SpatialReference; IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(sName, requiredFields, new UIDClass { Value = "esriGeoDatabase.Feature" }, null, esriFeatureType.esriFTSimple, shapeFieldName, ""); try { foreach (ROIGeometry roi in geometryList) { IFeature feature = featureClass.CreateFeature(); feature.Shape = roi.geometry; feature.Store(); } if (!string.IsNullOrEmpty(sAlias)) { EngineAPI.AlterDatasetAlias(featureClass, sAlias); } } finally { if (featureClass != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(featureClass); } } result = true; } catch { result = false; } return(result); }
/// <summary> /// /// </summary> /// <param name="featureDataset"></param> /// <param name="strNameOfFeatureClass"></param> /// <param name="isDissolved"></param> /// <returns></returns> public static IFeatureClass CreateCurveAreaFeatureClass(IFeatureDataset featureDataset, String strNameOfFeatureClass, bool isDissolved) { // This function creates a new feature class in a supplied feature dataset by building all of the // fields from scratch. IFeatureClassDescription (or IObjectClassDescription if the table is // created at the workspace level) can be used to get the required fields and are used to // get the InstanceClassID and ExtensionClassID. // Create new fields collection with the number of fields you plan to add. Must add at least two fields // for a feature class: Object ID and Shape field. // Create a feature class description object to use for specifying the CLSID and EXTCLSID. IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc; return(featureDataset.CreateFeatureClass(strNameOfFeatureClass, GetCurveAreaFields(false, isDissolved), ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "SHAPE", "")); }
private IFeatureClass CreateNewFeatureClass(IWorkspace pWS, String featureClassName, IFields pFields, esriFeatureType pEsriFeatureType) { IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = fcDesc as IObjectClassDescription; IFieldChecker pFieldChecker = new FieldCheckerClass(); IEnumFieldError pEnumFieldError = null; IFields validatedFields = null; IFeatureWorkspace pFeatureWorkspace = pWS as IFeatureWorkspace; pFieldChecker.ValidateWorkspace = pWS; pFieldChecker.Validate(pFields, out pEnumFieldError, out validatedFields); IFeatureClass pFeatureClass = pFeatureWorkspace.CreateFeatureClass(featureClassName, validatedFields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, pEsriFeatureType, fcDesc.ShapeFieldName, ""); return(pFeatureClass); }
public string GenerateTempProfileLinesStorage() { IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)calcWorkspace; workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); string newFeatureClassName = $"{calcFeatureClass}{MilSpace.DataAccess.Helper.GetTemporaryNameSuffix()}"; IWorkspace2 wsp2 = (IWorkspace2)calcWorkspace; IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)calcWorkspace; if (!wsp2.get_NameExists(esriDatasetType.esriDTFeatureClass, newFeatureClassName)) { IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; IFields fields = ocDescription.RequiredFields; // Find the shape field in the required fields and modify its GeometryDef to // use point geometry and to set the spatial reference. int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; geometryDefEdit.SpatialReference_2 = ArcMapInstance.Document.FocusMap.SpatialReference;; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; IField nameField = new FieldClass(); IFieldEdit nameFieldEdit = (IFieldEdit)nameField; nameFieldEdit.Name_2 = "ID"; nameFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(nameField); IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(newFeatureClassName, fields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "shape", ""); } workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); return(newFeatureClassName); }
//using a class description object创建一个新要素类,并赋予空间参考和要素类型 private IFeatureClass CreateFeatureClass(String featureClassName, IFeatureWorkspace featureWorkspace, ISpatialReference spatialReference) { //实例化要素类描述对象,获得默认字段 IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; IFields fields = ocDescription.RequiredFields; // 找到图形字段定义空间参考和类型 int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; geometryDefEdit.SpatialReference_2 = spatialReference; IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, fields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); return(featureClass); }
/// <summary> /// Creates the photo featureclass. /// </summary> /// <param name="workspace">The workspace.</param> /// <param name="featureclassname">The featureclassname.</param> /// <returns>IFeatureClass for GPS Photos</returns> private IFeatureClass CreatePhotoFeatureclass(IWorkspace workspace, string featureclassname) { ISpatialReference spatialReference = Utility.GetWGS84SpatialReference(); IFeatureClassDescription featureclassDesc = new FeatureClassDescriptionClass(); IObjectClassDescription objectclassDesc = (IObjectClassDescription)featureclassDesc; try { IFeatureClass featureclass = this.CreateFeatureClass((IFeatureWorkspace)workspace, featureclassname, spatialReference); return(featureclass); } catch (Exception ex) { Trace.WriteLine(ex.StackTrace); throw; } }
//用帮助里的例子,修改了字段和空间参考 public IFeatureClass CreateFeatureClass(String featureClassName, IFeatureWorkspace featureWorkspace, IField[] arrFields) { // Instantiate a feature class description to get the required fields. IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; IFields fields = ocDescription.RequiredFields; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; // Add some fields to the required fields. foreach (IField pField in arrFields) { fieldsEdit.AddField(pField); } // Find the shape field in the required fields and modify its GeometryDef to // use point geometry and to set the spatial reference. int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; geometryDefEdit.SpatialReference_2 = this.pMapControl.SpatialReference;//导进来的要素类使用当前地图的空间参考 // 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.//这一步极易出错,一般都是名为featureClassName的文件已存在 IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); return(featureClass); }
private IFields method_1() { if (NewObjectClassHelper.m_pObjectClassHelper.IsFeatureClass) { IFeatureClassDescription description; IFields requiredFields; IGeometryDef geometryDef; if (NewObjectClassHelper.m_pObjectClassHelper.FeatureType == esriFeatureType.esriFTSimple) { description = new FeatureClassDescriptionClass(); requiredFields = (description as IObjectClassDescription).RequiredFields; IField field = requiredFields.get_Field(requiredFields.FindField(description.ShapeFieldName)); geometryDef = (field as IFieldEdit2).GeometryDef; (geometryDef as IGeometryDefEdit).GeometryType_2 = NewObjectClassHelper.m_pObjectClassHelper.ShapeType; (field as IFieldEdit).GeometryDef_2 = geometryDef as IGeometryDefEdit; return(requiredFields); } if (NewObjectClassHelper.m_pObjectClassHelper.FeatureType == esriFeatureType.esriFTAnnotation) { description = new AnnotationFeatureClassDescriptionClass(); requiredFields = (description as IObjectClassDescription).RequiredFields; geometryDef = (requiredFields.get_Field(requiredFields.FindField(description.ShapeFieldName)) as IFieldEdit2) .GeometryDef; return(requiredFields); } if (NewObjectClassHelper.m_pObjectClassHelper.FeatureType == esriFeatureType.esriFTDimension) { description = new DimensionClassDescriptionClass(); requiredFields = (description as IObjectClassDescription).RequiredFields; geometryDef = (requiredFields.get_Field(requiredFields.FindField(description.ShapeFieldName)) as IFieldEdit2) .GeometryDef; return(requiredFields); } return(null); } IObjectClassDescription description2 = new FeatureClassDescriptionClass(); return(description2.RequiredFields); }
private IFeatureClass method_2(IFeatureWorkspace ifeatureWorkspace_0, string string_4, esriFeatureType esriFeatureType_0, esriGeometryType esriGeometryType_0, IFields ifields_0) { IFeatureClass class2 = null; string str; IFieldChecker checker = new FieldCheckerClass { ValidateWorkspace = ifeatureWorkspace_0 as IWorkspace }; checker.ValidateTableName(string_4, out str); IObjectClassDescription description = null; if (esriFeatureType_0 == esriFeatureType.esriFTAnnotation) { return(this.method_1(ifeatureWorkspace_0, string_4, 1000.0, new TextSymbolClass(), ifields_0)); } description = new FeatureClassDescriptionClass(); IFieldsEdit requiredFields = description.RequiredFields as IFieldsEdit; IFieldEdit edit2 = null; int index = requiredFields.FindField((description as IFeatureClassDescription).ShapeFieldName); edit2 = requiredFields.get_Field(index) as IFieldEdit; IGeometryDefEdit geometryDef = edit2.GeometryDef as IGeometryDefEdit; esriFeatureType esriFTSimple = esriFeatureType.esriFTSimple; edit2.GeometryDef_2 = geometryDef; for (int i = 0; i < ifields_0.FieldCount; i++) { requiredFields.AddField(ifields_0.get_Field(i)); } try { class2 = ifeatureWorkspace_0.CreateFeatureClass(string_4, requiredFields, null, null, esriFTSimple, (description as IFeatureClassDescription).ShapeFieldName, ""); } catch (Exception exception) { Logger.Current.Error("", exception, ""); } return(class2); }
public IFeatureClass CreateFeatureDatasetFeatureClass(IFeatureDataset featureDataset, String featureClassName, IFields fieldsCollection, esriFeatureType featureType, String shapeFieldName) { IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc; // Use IFieldChecker to create a validated fields collection. IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = featureDataset.Workspace; fieldChecker.Validate(fieldsCollection, out enumFieldError, out validatedFields); // The enumFieldError enumerator can be inspected at this point to determine // which fields were modified during validation. IFeatureClass featureClass = featureDataset.CreateFeatureClass(featureClassName, validatedFields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDesc.ShapeFieldName, ""); return(featureClass); }
private IFields CreateFieldsCollection(ISpatialReference spatialReference, esriGeometryType geometryType) { IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = fcDesc as IObjectClassDescription; IFields fields = ocDesc.RequiredFields; IFieldsEdit fieldsEdit = fields as IFieldsEdit; int shapeFieldIndex = fields.FindField(fcDesc.ShapeFieldName); IField shapeField = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = shapeField.GeometryDef; IGeometryDefEdit geometryDefEdit = geometryDef as IGeometryDefEdit; geometryDefEdit.GeometryType_2 = geometryType; geometryDefEdit.GridCount_2 = 1; geometryDefEdit.set_GridSize(0, 0); geometryDefEdit.SpatialReference_2 = spatialReference; return(fields); }
public IFeatureClass CreateFeatureClass(String featureClassName, IFeatureWorkspace featureWorkspace) { CreateFieldForm f = new CreateFieldForm(); if (f.ShowDialog() == DialogResult.OK) { try { IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; IFields fields = ocDescription.RequiredFields; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; for (int i = 0; i < MyGlobalClass.fields.Length; i++) { IField field = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = MyGlobalClass.fields[i].name; fieldEdit.Type_2 = MyGlobalClass.fields[i].type; fieldsEdit.AddField(field); } IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = (IWorkspace)featureWorkspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); return(featureClass); } catch (Exception ex) { MessageBox.Show("Error is function CreateFeatureClass: " + ex.Message); } } return(null); }
public static IFeatureClass CreateSignsFeatureClass(IFeatureClass linesFeatureClass, string name) { // Locations are all relative to the location of the reference lines. // For geodatabase, signs feature class is at the same location and the streets table // is at the level of the containing feature dataset. // For shapefile, both are at the same location as the reference lines. // start with the initial set of required fields for a feature class IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = fcDescription as IObjectClassDescription; IFieldsEdit outFields = ocDescription.RequiredFields as IFieldsEdit; // make the shape field to be of type polyline with the same spatial reference as the reference lines IField shapeField = outFields.get_Field(outFields.FindField(fcDescription.ShapeFieldName)); IGeometryDefEdit geomDefEdit = shapeField.GeometryDef as IGeometryDefEdit; geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; geomDefEdit.SpatialReference_2 = (linesFeatureClass as IGeoDataset).SpatialReference; // add the other fields to the feature class IFieldEdit field = new FieldClass(); field.Name_2 = "ExitName"; field.Type_2 = esriFieldType.esriFieldTypeString; field.Length_2 = 24; outFields.AddField(field); string currentNumber; for (int i = 0; i < MaxBranchCount; i++) { currentNumber = Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture); field = new FieldClass(); field.Name_2 = "Branch" + currentNumber; field.Type_2 = esriFieldType.esriFieldTypeString; field.Length_2 = 180; outFields.AddField(field); field = new FieldClass(); field.Name_2 = "Branch" + currentNumber + "Dir"; field.Type_2 = esriFieldType.esriFieldTypeString; field.Length_2 = 5; outFields.AddField(field); field = new FieldClass(); field.Name_2 = "Branch" + currentNumber + "Lng"; field.Type_2 = esriFieldType.esriFieldTypeString; field.Length_2 = 2; outFields.AddField(field); field = new FieldClass(); field.Name_2 = "Toward" + currentNumber; field.Type_2 = esriFieldType.esriFieldTypeString; field.Length_2 = 180; outFields.AddField(field); field = new FieldClass(); field.Name_2 = "Toward" + currentNumber + "Lng"; field.Type_2 = esriFieldType.esriFieldTypeString; field.Length_2 = 2; outFields.AddField(field); } // make the feature class IFeatureDataset pFeatureDataset = linesFeatureClass.FeatureDataset; IWorkspace pWorkspace = (linesFeatureClass as IDataset).Workspace; if (pFeatureDataset != null) return pFeatureDataset.CreateFeatureClass(name, outFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); else if (pWorkspace is IFeatureWorkspace) return (pWorkspace as IFeatureWorkspace).CreateFeatureClass(name, outFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); else return null; // not expected }
/// <summary> /// Add Feature class and its feilds /// </summary> /// <param name="featureClassName"></param> /// <param name="featureWorkspace"></param> /// <returns></returns> public IFeatureClass CreateFeatureClassWithFields(String featureClassName, IFeatureWorkspace featureWorkspace, string dir) { GeoJson geoJson = new GeoJson(); try { _featureInJSON = geoJson.readGeoJsonFile(dir); // Instantiate a feature class description to get the required fields. IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription) fcDescription; IFields fields = ocDescription.RequiredFields; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; for (int i = 0; i < 9; i++) { if (_featureInJSON.fields[i].name == "OBJECTID") continue; else addFeatureFeild(_featureInJSON.fields[i].name, _featureInJSON.fields[i].alias, (esriFieldType)Enum.Parse(typeof(esriFieldType), _featureInJSON.fields[i].type), fieldsEdit); } // 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. IFeatureClass featureClass = featureWorkspace.CreateFeatureClass (featureClassName, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); return featureClass; } catch (Exception e) { Log.WriteLine("CreateFeatureClassWithFields: " + e.Message); } return null; }
public IFeatureClass CreateFeatureClassWithFieldsGeoRef(String featureClassName, IFeatureWorkspace featureWorkspace) { GeoJson geoJson = new GeoJson(); try { // Instantiate a feature class description to get the required fields. IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription) fcDescription; IFields fields = ocDescription.RequiredFields; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; addFeatureFeild("URI", "URI", esriFieldType.esriFieldTypeString, fieldsEdit); // 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. IFeatureClass featureClass = featureWorkspace.CreateFeatureClass (featureClassName, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); return featureClass; } catch (Exception e) { Log.WriteLine("CreateFeatureClassWithFields: " + e.Message); } return null; }
public static IFeatureClass createGoogleMapsEngineCatalogFeatureClass(ref log4net.ILog log, ref GoogleMapsEngineToolsExtensionForArcGIS ext) { try { // temporary directory to store workspace string workspacedirectory = ext.getLocalWorkspaceDirectory().FullName; // add the directory to the cleanup list // TODO: Replace with scratch ext.addTemporaryDirectory(new System.IO.DirectoryInfo(workspacedirectory)); // determine the workspace name for the geodatabase //string workspacefoldername = Properties.Settings.Default.extension_gdb_workspacename; // TODO: Use sctach workspace instead of creating a temporary one string workspacefoldername = "GME_Data_" + System.Guid.NewGuid().ToString().Replace("-", ""); // define a workspace to do work IWorkspace workspace = null; // attempt to open or create the workspace try { // check to see if the workspace already exists, if so, open it if (System.IO.Directory.Exists(workspacedirectory + "\\" + workspacefoldername)) { workspace = Extension.Data.GeodatabaseUtilities.openFileGeodatabaseWorkspace(ref log, workspacedirectory, workspacefoldername); ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace; ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(Properties.Resources.GeodatabaseUtilities_schema_FeatureClassName); ESRI.ArcGIS.Geodatabase.IDataset pdataset = (ESRI.ArcGIS.Geodatabase.IDataset)featureClass; if (pdataset.CanDelete()) pdataset.Delete(); pdataset = null; featureClass = null; featureWorkspace = null; // TODO: Open instead of delete/replace //if (arcgis.ext.gdb.GeodatabaseUtilities.deleteFileGeodatabaseWorkspace(workspacedirectory, workspacefoldername)) //workspace = arcgis.ext.gdb.GeodatabaseUtilities.createFileGeodatabaseWorkspace(workspacedirectory, workspacefoldername); } else { // workspace doesn't exist, create the workspace workspace = Extension.Data.GeodatabaseUtilities.createFileGeodatabaseWorkspace(ref log, workspacedirectory, workspacefoldername); } } catch (System.Exception ex) { // unable to create the fgdb or unable to delete the fc within the fgdb log.Error(ex); System.Windows.Forms.MessageBox.Show("Unable to create or delete an existing feature class."); } // verify the workspace is open if (workspace != null) { // create a new feature workspace to work spatially IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; // create a spatial reference for the Google Earth Builder data (always in 4326) SpatialReferenceEnvironment sRefEnvGEB = new SpatialReferenceEnvironment(); ISpatialReference sGEBRef = sRefEnvGEB.CreateGeographicCoordinateSystem(4326); // for this feature class, create and determine the field IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; fieldsEdit.FieldCount_2 = 10; //Create the Object ID field. IField fusrDefinedField = new Field(); IFieldEdit fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_OBJECTID_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_OBJECTID_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.set_Field(0, fusrDefinedField); //Create the CustomerId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_CustomerId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(1, fusrDefinedField); //Create the MapAssetId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(2, fusrDefinedField); //Create the AssetId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(3, fusrDefinedField); //Create the ParentAssetId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(4, fusrDefinedField); //Create the AssetType field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetType_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(5, fusrDefinedField); //Create the AssetName field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetName_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(6, fusrDefinedField); //Create the AssetDescription field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(7, fusrDefinedField); //Create the MapSharedWith field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_MapSharedWith_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_MapSharedWith_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(8, fusrDefinedField); // Create the Shape field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; // Set up the geometry definition for the Shape field. IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon; // By setting the grid size to 0, you're allowing ArcGIS to determine the appropriate grid sizes for the feature class. // If in a personal geodatabase, the grid size will be 1000. If in a file or ArcSDE geodatabase, the grid size // will be based on the initial loading or inserting of features. geometryDefEdit.GridCount_2 = 1; geometryDefEdit.set_GridSize(0, 0); geometryDefEdit.HasM_2 = false; geometryDefEdit.HasZ_2 = false; //Assign the spatial reference that was passed in, possibly from //IGeodatabase.SpatialReference for the containing feature dataset. geometryDefEdit.SpatialReference_2 = sGEBRef; // Set standard field properties. fusrDefinedFieldEdit.Name_2 = "SHAPE"; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; fusrDefinedFieldEdit.GeometryDef_2 = geometryDef; fusrDefinedFieldEdit.IsNullable_2 = true; fusrDefinedFieldEdit.Required_2 = true; fieldsEdit.set_Field(9, fusrDefinedField); // Create a feature class description object to use for specifying the CLSID and EXTCLSID. IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc; IFeatureClass fc = featureWorkspace.CreateFeatureClass( Properties.Resources.GeodatabaseUtilities_schema_FeatureClassName, // Feature Class Name fields, // Feature Class Fields (defined above) ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDesc.ShapeFieldName, // Shape Field Name "" // Keyword Configurations ); // return the feature class return fc; } else { // end gracefully, maybe prompt the user that the toolbar wasn't able to create a workspcae throw new Exception("Unable to open local geodatabase."); } } catch (System.Exception ex) { // an error occured log.Error(ex); // throw an exception throw new Exception("An unknown exception occured while attempting to create a local feature class."); } }
//This is the full GPX 1.1 schema. //Option 1 - Add all schema defined fields, even if they are not used //TODO - Option 2 - Scan file and only use fields used in this file. //var search = Root.Descendants(_ns + type.Path); private IFields BuildFields(GpxFeatureClass featureClass) { var description = new FeatureClassDescriptionClass(); var fields = (IFieldsEdit)description.RequiredFields; IFieldEdit field = new FieldClass(); //Geometry var geometryIndex = fields.FindField(description.ShapeFieldName); var geometry = (IGeometryDefEdit)fields.Field[geometryIndex].GeometryDef; geometry.GeometryType_2 = featureClass.GeometryType; geometry.SpatialReference_2 = SpatialReference; geometry.HasM_2 = false; geometry.HasZ_2 = true; //FIXME - this may be false. //Common Fields field.Name_2 = "name"; field.AliasName_2 = "Name"; field.Type_2 = esriFieldType.esriFieldTypeString; fields.AddField(field); // ReSharper disable UseObjectOrCollectionInitializer //These COM classes do not support object initializers field = new FieldClass(); field.Name_2 = "cmt"; field.AliasName_2 = "Comment"; field.Type_2 = esriFieldType.esriFieldTypeString; fields.AddField(field); field = new FieldClass(); field.Name_2 = "desc"; field.AliasName_2 = "Description"; field.Type_2 = esriFieldType.esriFieldTypeString; fields.AddField(field); field = new FieldClass(); field.Name_2 = "src"; field.AliasName_2 = "Source"; field.Type_2 = esriFieldType.esriFieldTypeString; fields.AddField(field); field = new FieldClass(); field.Name_2 = "link"; field.AliasName_2 = "Hyperlink"; //field.Type_2 = esriFieldType.esriFieldTypeXML; //XML datatype is not fully supported in Desktop (i.e. no value is displayed, and export to shapefile will fail) field.Type_2 = esriFieldType.esriFieldTypeString; fields.AddField(field); //GPX 1.0 field = new FieldClass(); field.Name_2 = "url"; field.AliasName_2 = "Url link"; field.Type_2 = esriFieldType.esriFieldTypeString; fields.AddField(field); //GPX 1.0 field = new FieldClass(); field.Name_2 = "urlname"; field.AliasName_2 = "Url Name"; field.Type_2 = esriFieldType.esriFieldTypeString; fields.AddField(field); field = new FieldClass(); field.Name_2 = "type"; field.AliasName_2 = "Type"; field.Type_2 = esriFieldType.esriFieldTypeString; fields.AddField(field); field = new FieldClass(); field.Name_2 = "extensions"; //field.Type_2 = esriFieldType.esriFieldTypeXML; field.Type_2 = esriFieldType.esriFieldTypeString; fields.AddField(field); //Only for Routes and Tracks if (featureClass.Path == "rte" || featureClass.Path == "trk") { field = new FieldClass(); field.Name_2 = "number"; field.AliasName_2 = featureClass.Path == "rte" ? "Route Number" : "Track Number"; field.Type_2 = esriFieldType.esriFieldTypeInteger; fields.AddField(field); } //Only for Points if (featureClass.Path == "wpt" || featureClass.Path == "trkpt" || featureClass.Path == "rtept") { field = new FieldClass(); field.Name_2 = "ele"; field.AliasName_2 = "Elevation"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fields.AddField(field); field = new FieldClass(); field.Name_2 = "time"; field.AliasName_2 = "Time (UTC)"; field.Type_2 = esriFieldType.esriFieldTypeDate; fields.AddField(field); field = new FieldClass(); field.Name_2 = "magvar"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fields.AddField(field); field = new FieldClass(); field.Name_2 = "geoidheight"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fields.AddField(field); field = new FieldClass(); field.Name_2 = "sym"; field.AliasName_2 = "Symbol"; field.Type_2 = esriFieldType.esriFieldTypeString; fields.AddField(field); field = new FieldClass(); field.Name_2 = "fix"; field.AliasName_2 = "GpsFix"; field.Type_2 = esriFieldType.esriFieldTypeString; field.Length_2 = 4; fields.AddField(field); field = new FieldClass(); field.Name_2 = "sat"; field.AliasName_2 = "Satellites"; field.Type_2 = esriFieldType.esriFieldTypeInteger; fields.AddField(field); field = new FieldClass(); field.Name_2 = "hdop"; field.AliasName_2 = "HDOP"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fields.AddField(field); field = new FieldClass(); field.Name_2 = "vdop"; field.AliasName_2 = "VDOP"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fields.AddField(field); field = new FieldClass(); field.Name_2 = "pdop"; field.AliasName_2 = "PDOP"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fields.AddField(field); field = new FieldClass(); field.Name_2 = "ageofdgpsdata"; field.Type_2 = esriFieldType.esriFieldTypeDouble; fields.AddField(field); field = new FieldClass(); field.Name_2 = "dgpsid"; field.Type_2 = esriFieldType.esriFieldTypeInteger; fields.AddField(field); // ReSharper restore UseObjectOrCollectionInitializer } return fields; }
/// <summary> /// creates a new featrue class /// </summary> /// <param name="wks">the workspace to create from</param> /// <param name="polyFtrClsName">name of the feature class</param> /// <param name="atrflds">name of the fields</param> /// <param name="geoType">the geotype</param> /// <param name="sr">spatial reference</param> /// <returns>newly created featureclass</returns> public IFeatureClass createFeatureClass(IWorkspace2 wks, string polyFtrClsName, IFields atrflds, esriGeometryType geoType, ISpatialReference sr) { IFeatureClass tFtr = null; try { IFeatureWorkspace ftrWks = (IFeatureWorkspace)wks; polyFtrClsName = getSafeOutputNameNonRaster((IWorkspace)wks, polyFtrClsName); IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; IFields fields = ocDescription.RequiredFields; if (atrflds != null) { IFieldsEdit fieldsEdit = (IFieldsEdit)fields; for (int i = 0; i < atrflds.FieldCount; i++) { IField fld = atrflds.get_Field(i); IField nFld = new FieldClass(); IFieldEdit nFldE = (IFieldEdit)nFld; nFldE.Name_2 = fld.Name; if (fld.Type != esriFieldType.esriFieldTypeOID) { nFldE.Type_2 = fld.Type; fieldsEdit.AddField(nFld); } } } // Find the shape field in the required fields and modify its GeometryDef to// use point geometry and to set the spatial reference.int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(fields.FindField(fcDescription.ShapeFieldName)); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = geoType; geometryDefEdit.SpatialReference_2 = sr; // Use IFieldChecker to create a validated fields collection. IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = (IWorkspace)wks; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); tFtr = ftrWks.CreateFeatureClass(polyFtrClsName, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); } catch(Exception e) { Console.WriteLine("Error: " + e.ToString()); } return tFtr; }
public static IFeatureClass CreateFeatureClass(IWorkspace workspace, IFeatureDataset featureDataset, String featureClassName, IFields fields) { IFeatureClass featureClass; String strShapeField = ""; var featureWorkspace = workspace as IFeatureWorkspace; IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass(); #region 简单校验 if (featureClassName == "") return null; //if (workspace.get_NameExists(esriDatasetType.esriDTFeatureClass, featureClassName)) //{ // featureClass = featureWorkspace.OpenFeatureClass(featureClassName); // return featureClass; //} if (fields == null) { fields = objectClassDescription.RequiredFields; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; IField field = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Name"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.AddField(field); fields = (IFields)fieldsEdit; } var feaClsDes = objectClassDescription as IFeatureClassDescription; strShapeField = feaClsDes.ShapeFieldName; #endregion //查询几何字段 if (strShapeField == "") { for (int j = 0; j < fields.FieldCount; j++) { if (fields.get_Field(j).Type == esriFieldType.esriFieldTypeGeometry) { strShapeField = fields.get_Field(j).Name; } } } // 字段检查 IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = (IWorkspace)workspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); //创建要素类 if (featureDataset == null) { featureClass = featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, strShapeField, ""); } else { featureClass = featureDataset.CreateFeatureClass(featureClassName, validatedFields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, strShapeField, ""); } return featureClass; }
/// <summary>Create a feature class in a existing FGDB </summary> /// <param name="FGDBPath">Path to the existing FGDB</param> /// <param name="FCname">Name of the new FeatureClass</param> /// <param name="field2add">List of Ifields</param> /// <param name="srs">the srs of the shapefile</param> /// <param name="geomType">the type geometry: point, polyline, polygon, ...</param> /// <param name="deleteIfExists">Overwrite existing FeatureClass</param> /// <returns>the Feuture Class loaded in a IFeatureClass</returns> public static IFeatureClass createFeatureClass(string FGDBPath, string FCname, List<IField> field2add, ISpatialReference srs, esriGeometryType geomType, bool deleteIfExists = true) { DirectoryInfo fgbInfo = new DirectoryInfo(FGDBPath); if (FGDBPath == "" || FCname == "") return null; // name was not passed in IFeatureClass featureClass; // Instantiate a feature class description to get the required fields. IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = fcDescription as IObjectClassDescription; IFields fields = ocDescription.RequiredFields; IFieldsEdit fieldsEdit = (IFieldsEdit) fields ; // Find the shape field in the required fields and modify its GeometryDef to // use wanted geometry and to set the spatial reference. IField shapeField = null; for (int j = 0; j < fields.FieldCount; j++) { if (fields.get_Field(j).Type == ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeGeometry) { shapeField = fields.get_Field(j); break; } } if (shapeField == null) return null; int shapeFieldIndex = fields.FindField(shapeField.Name); IField geofield = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = geofield.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = geomType; geometryDefEdit.SpatialReference_2 = srs; foreach (IField field in field2add) { fieldsEdit.AddField(field); } IWorkspaceFactory2 workspaceFactory = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass(); IWorkspace2 workspace = (IWorkspace2)workspaceFactory.OpenFromFile(FGDBPath, 0); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace; string validatedName = ValidateTableName((IWorkspace)workspace, FCname); if (workspace.get_NameExists(esriDatasetType.esriDTFeatureClass, validatedName)) { if (deleteIfExists) { if (!deleteFeatureClass(fgbInfo.FullName + "\\" + validatedName)) { throw new Exception(validatedName + " exists and cannot be deleted"); } } else { throw new Exception(validatedName + " exists"); } } IFields validatedFields = validateFields((IWorkspace) workspace, fields); //create the feature class featureClass = featureWorkspace.CreateFeatureClass(validatedName, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, shapeField.Name, ""); return featureClass; }
///<summary>Simple helper to create a featureclass in a geodatabase.</summary> /// ///<param name="workspace">An IWorkspace2 interface</param> ///<param name="featureDataset">An IFeatureDataset interface or Nothing</param> ///<param name="featureClassName">A System.String that contains the name of the feature class to open or create. Example: "states"</param> ///<param name="fields">An IFields interface</param> ///<param name="clsid">A UID value or Nothing. Example "esriGeoDatabase.Feature" or Nothing</param> ///<param name="clsext">A UID value or Nothing (this is the class extension if you want to reference a class extension when creating the feature class).</param> ///<param name="strConfigKeyword">An empty System.String or RDBMS table string for ArcSDE. Example: "myTable" or ""</param> /// ///<returns>An IFeatureClass interface or a Nothing</returns> /// ///<remarks> /// (1) If a 'featureClassName' already exists in the workspace a reference to that feature class /// object will be returned. /// (2) If an IFeatureDataset is passed in for the 'featureDataset' argument the feature class /// will be created in the dataset. If a Nothing is passed in for the 'featureDataset' /// argument the feature class will be created in the workspace. /// (3) When creating a feature class in a dataset the spatial reference is inherited /// from the dataset object. /// (4) If an IFields interface is supplied for the 'fields' collection it will be used to create the /// table. If a Nothing value is supplied for the 'fields' collection, a table will be created using /// default values in the method. /// (5) The 'strConfigurationKeyword' parameter allows the application to control the physical layout /// for this table in the underlying RDBMSfor example, in the case of an Oracle database, the /// configuration keyword controls the tablespace in which the table is created, the initial and /// next extents, and other properties. The 'strConfigurationKeywords' for an ArcSDE instance are /// set up by the ArcSDE data administrator, the list of available keywords supported by a workspace /// may be obtained using the IWorkspaceConfiguration interface. For more information on configuration /// keywords, refer to the ArcSDE documentation. When not using an ArcSDE table use an empty /// string (ex: ""). ///</remarks> internal IFeatureClass CreateFeatureClass(IWorkspace2 workspace, IFeatureDataset featureDataset, string featureClassName, IFields fields, ESRI.ArcGIS.esriSystem.UID clsid, ESRI.ArcGIS.esriSystem.UID clsext, string strConfigKeyword) { if (string.IsNullOrEmpty(featureClassName)) return null; IFeatureClass featureClass; var featureWorkspace = (IFeatureWorkspace)workspace; // Cast may throw exception if (workspace.NameExists[esriDatasetType.esriDTFeatureClass, featureClassName]) //feature class with that name already exists { featureClass = featureWorkspace.OpenFeatureClass(featureClassName); return featureClass; } // assign the class id value if not assigned if (clsid == null) { clsid = new ESRI.ArcGIS.esriSystem.UIDClass { Value = "esriGeoDatabase.Feature" }; //Works for shapefiles as well } IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass(); // if a fields collection is not passed in then supply our own if (fields == null) { // create the fields using the required fields method fields = objectClassDescription.RequiredFields; var fieldsEdit = (IFieldsEdit)fields; // Explicit Cast IField field = new FieldClass(); // create a user defined text field var fieldEdit = (IFieldEdit)field; // Explicit Cast // 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 = fieldsEdit; } string strShapeField = ""; // locate the shape field for (int j = 0; j < fields.FieldCount; j++) { if (fields.Field[j].Type != esriFieldType.esriFieldTypeGeometry) continue; strShapeField = fields.Field[j].Name; break; } // Use IFieldChecker to create a validated fields collection. IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError; IFields validatedFields; fieldChecker.ValidateWorkspace = (IWorkspace)workspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); // The enumFieldError enumerator can be inspected at this point to determine // which fields were modified during validation. // finally create and return the feature class featureClass = featureDataset == null ? featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, clsid, clsext, esriFeatureType.esriFTSimple, strShapeField, strConfigKeyword) : featureDataset.CreateFeatureClass(featureClassName, validatedFields, clsid, clsext, esriFeatureType.esriFTSimple, strShapeField, strConfigKeyword); return featureClass; }
/// <summary> /// 创建一个新的FeatureClass /// </summary> /// <param name="FeatureWorkspace">要素命名空间</param> /// <param name="Name">名称</param> /// <param name="esriGeometryType">类型</param> /// <param name="FieldDict">字段已经类型</param> /// <returns></returns> private static IFeatureClass Create(IFeatureWorkspace FeatureWorkspace, string Name, ESRI.ArcGIS.Geometry.esriGeometryType esriGeometryType,Dictionary<string,esriFieldType> FieldDict) { IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = pFields as IFieldsEdit; IField pField = new FieldClass(); IFieldEdit pFieldEdit = pField as IFieldEdit; pFieldEdit.Name_2 = "shape"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef pGeometryDef = new GeometryDefClass(); IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit; pGeometryDefEdit.GeometryType_2 = esriGeometryType; ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference pSpatialReference = pSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); pSpatialReference.SetDomain(-6000000, 6000000, -6000000, 6000000); pGeometryDefEdit.SpatialReference_2 = pSpatialReference; pFieldEdit.GeometryDef_2 = pGeometryDef; pFieldsEdit.AddField(pField); pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.Name_2 = "FID"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; pFieldsEdit.AddField(pField); foreach (var key in FieldDict.Keys) { if (key.ToUpper() == "SHAPE"||key.ToUpper()=="OBJECTID") { continue; } pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.Name_2 = key; pFieldEdit.Type_2 = FieldDict[key]; pFieldsEdit.AddField(pField); } IFeatureClassDescription featureClassDescription = new FeatureClassDescriptionClass(); IObjectClassDescription objectClassDescription = featureClassDescription as IObjectClassDescription; IFeatureClass featureClass = FeatureWorkspace.CreateFeatureClass(Name, pFields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "shape", ""); return featureClass; }
private void CreateAndPopulateTurnFeatureClass(string outputFileGdbPath, string fdsName, string ProhibRdmsTableName, string tempStatsTableName, IGPMessages messages, ITrackCancel trackcancel) { // Determine the number of AltID fields we need (one more than the MAX_SEQ_NUMBER value). Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory; var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace; ITable tempStatsTable = fws.OpenTable(tempStatsTableName); short numAltIDFields = 2; if (tempStatsTable.RowCount(null) == 1) numAltIDFields = (short)(1 + (double)(tempStatsTable.GetRow(1).get_Value(tempStatsTable.FindField("MAX_SEQ_NUMBER")))); // Open the Rdms table and find the fields we need ITable rdmsTable = fws.OpenTable(ProhibRdmsTableName); int seqNumberField = rdmsTable.FindField("SEQ_NUMBER"); int linkIDFieldOnRdms = rdmsTable.FindField("LINK_ID"); int manLinkIDField = rdmsTable.FindField("MAN_LINKID"); int condIDFieldOnRdms = rdmsTable.FindField("COND_ID"); int endOfLkFieldOnRdms = rdmsTable.FindField("END_OF_LK"); // Create a temporary template feature class var fcd = new FeatureClassDescriptionClass() as IFeatureClassDescription; var ocd = fcd as IObjectClassDescription; var fieldsEdit = ocd.RequiredFields as IFieldsEdit; IField fieldOnRdmsTable = rdmsTable.Fields.get_Field(linkIDFieldOnRdms); // use the LINK_ID field as a template for the AltID fields for (short i = 1; i <= numAltIDFields; i++) { IFieldEdit newField = new FieldClass(); newField.Name_2 = "AltID" + i; newField.Precision_2 = fieldOnRdmsTable.Precision; newField.Scale_2 = fieldOnRdmsTable.Scale; newField.Type_2 = fieldOnRdmsTable.Type; fieldsEdit.AddField(newField as IField); } fieldOnRdmsTable = rdmsTable.Fields.get_Field(condIDFieldOnRdms); fieldsEdit.AddField(fieldOnRdmsTable); var fieldChk = new FieldCheckerClass() as IFieldChecker; IEnumFieldError enumFieldErr = null; IFields validatedFields = null; fieldChk.ValidateWorkspace = fws as IWorkspace; fieldChk.Validate(fieldsEdit as IFields, out enumFieldErr, out validatedFields); var tempFC = fws.CreateFeatureClass("TheTemplate", validatedFields, ocd.InstanceCLSID, ocd.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcd.ShapeFieldName, "") as IDataset; // Create the turn feature class from the template, then delete the template Geoprocessor gp = new Geoprocessor(); CreateTurnFeatureClass createTurnFCTool = new CreateTurnFeatureClass(); string pathToFds = outputFileGdbPath + "\\" + fdsName; createTurnFCTool.out_location = pathToFds; createTurnFCTool.out_feature_class_name = TurnFCName; createTurnFCTool.maximum_edges = numAltIDFields; createTurnFCTool.in_template_feature_class = outputFileGdbPath + "\\TheTemplate"; gp.Execute(createTurnFCTool, trackcancel); tempFC.Delete(); // Open the new turn feature class and find all the fields on it IFeatureClass turnFC = fws.OpenFeatureClass(TurnFCName); int[] altIDFields = new int[numAltIDFields]; int[] edgeFCIDFields = new int[numAltIDFields]; int[] edgeFIDFields = new int[numAltIDFields]; int[] edgePosFields = new int[numAltIDFields]; for (short i = 0; i < numAltIDFields; i++) { altIDFields[i] = turnFC.FindField("AltID" + (i + 1)); edgeFCIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FCID"); edgeFIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FID"); edgePosFields[i] = turnFC.FindField("Edge" + (i + 1) + "Pos"); } int edge1endField = turnFC.FindField("Edge1End"); int condIDFieldOnTurnFC = turnFC.FindField("COND_ID"); // Look up the FCID of the Streets feature class IFeatureClass streetsFC = fws.OpenFeatureClass(StreetsFCName); int streetsFCID = streetsFC.FeatureClassID; // Set up queries var ts = new TableSortClass() as ITableSort; ts.Fields = "COND_ID, SEQ_NUMBER"; ts.set_Ascending("COND_ID", true); ts.set_Ascending("SEQ_NUMBER", true); ts.QueryFilter = new QueryFilterClass(); ts.Table = rdmsTable; ts.Sort(null); ICursor rdmsCursor = ts.Rows; IFeatureCursor turnFCCursor = turnFC.Insert(true); IFeatureBuffer turnBuffer = turnFC.CreateFeatureBuffer(); // Write the field values to the turn feature class accordingly int numFeatures = 0; IRow rdmsRow = rdmsCursor.NextRow(); while (rdmsRow != null) { // Transfer the non-edge identifying field values to the buffer turnBuffer.set_Value(condIDFieldOnTurnFC, rdmsRow.get_Value(condIDFieldOnRdms)); // Write the Edge1End field value to the buffer switch ((string)(rdmsRow.get_Value(endOfLkFieldOnRdms))) { case "N": turnBuffer.set_Value(edge1endField, "Y"); break; case "R": turnBuffer.set_Value(edge1endField, "N"); break; default: break; // not expected } // Write the AltID values to the buffer turnBuffer.set_Value(altIDFields[0], rdmsRow.get_Value(linkIDFieldOnRdms)); short seq = (short)(rdmsRow.get_Value(seqNumberField)); short lastEntry; do { lastEntry = seq; turnBuffer.set_Value(altIDFields[lastEntry], rdmsRow.get_Value(manLinkIDField)); rdmsRow = rdmsCursor.NextRow(); if (rdmsRow == null) break; seq = (short)(rdmsRow.get_Value(seqNumberField)); } while (seq != 1); // Zero-out the unused fields for (int i = lastEntry + 1; i < numAltIDFields; i++) turnBuffer.set_Value(altIDFields[i], 0); // Write the FCID and Pos field values to the buffer for (short i = 0; i < numAltIDFields; i++) { int altID = (int)(turnBuffer.get_Value(altIDFields[i])); if (altID != 0) { turnBuffer.set_Value(edgeFCIDFields[i], streetsFCID); turnBuffer.set_Value(edgeFIDFields[i], 1); turnBuffer.set_Value(edgePosFields[i], 0.5); } else { turnBuffer.set_Value(edgeFCIDFields[i], 0); turnBuffer.set_Value(edgeFIDFields[i], 0); turnBuffer.set_Value(edgePosFields[i], 0); } } // Create the turn feature turnFCCursor.InsertFeature(turnBuffer); numFeatures++; if ((numFeatures % 100) == 0) { // check for user cancel if (trackcancel != null && !trackcancel.Continue()) throw (new COMException("Function cancelled.")); } } // Flush any outstanding writes to the turn feature class turnFCCursor.Flush(); messages.AddMessage("Updating the EdgeFID values..."); // Create a temporary network dataset for updating the EdgeFID values IDENetworkDataset dends = new DENetworkDatasetClass(); dends.SupportsTurns = true; dends.Buildable = true; (dends as IDataElement).Name = StreetsFCName; (dends as IDEGeoDataset).SpatialReference = (streetsFC as IGeoDataset).SpatialReference; IArray sourceArray = new ArrayClass(); var efs = new EdgeFeatureSourceClass() as IEdgeFeatureSource; (efs as INetworkSource).Name = StreetsFCName; efs.UsesSubtypes = false; efs.ClassConnectivityGroup = 1; efs.ClassConnectivityPolicy = esriNetworkEdgeConnectivityPolicy.esriNECPEndVertex; sourceArray.Add(efs); var tfs = new TurnFeatureSourceClass() as INetworkSource; tfs.Name = TurnFCName; sourceArray.Add(tfs); dends.Sources = sourceArray; var fdxc = fws.OpenFeatureDataset(fdsName) as IFeatureDatasetExtensionContainer; var dsCont = fdxc.FindExtension(esriDatasetType.esriDTNetworkDataset) as IDatasetContainer2; var tempNDS = dsCont.CreateDataset(dends as IDEDataset) as IDataset; // Set the EdgeFID field values by running UpdateByAlternateIDFields UpdateByAlternateIDFields updateByAltIDTool = new UpdateByAlternateIDFields(); updateByAltIDTool.in_network_dataset = pathToFds + "\\" + StreetsFCName; updateByAltIDTool.alternate_ID_field_name = "LINK_ID"; gp.Execute(updateByAltIDTool, trackcancel); // Delete the temporary network dataset tempNDS.Delete(); // Write the turn geometries TurnGeometryUtilities.WriteTurnGeometry(outputFileGdbPath, StreetsFCName, TurnFCName, numAltIDFields, 0.3, messages, trackcancel); // Index the turn geometries messages.AddMessage("Creating spatial index on the turn feature class..."); AddSpatialIndex addSpatialIndexTool = new AddSpatialIndex(); addSpatialIndexTool.in_features = pathToFds + "\\" + TurnFCName; gp.Execute(addSpatialIndexTool, trackcancel); return; }
public static void CreatePolygonFeature(IPolygon pPolygon, string shpfolder, string shpname) { IWorkspaceFactory pWorkSpaceFac = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWorkSpace = pWorkSpaceFac.OpenFromFile(shpfolder, 0) as IFeatureWorkspace; try {//如果图层存在则删除 FileInfo fFile = new FileInfo(shpfolder + @"\" + shpname + ".shp");// if (fFile.Exists) { DirectoryInfo fold = new DirectoryInfo(shpfolder); FileInfo[] files = fold.GetFiles(shpname + ".*"); foreach (FileInfo f in files) { f.Delete(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } //创建字段集2 IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;//创建必要字段 IFields fields = ocDescription.RequiredFields; int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass(); IGeographicCoordinateSystem pcsSys = pSpatialRefFac.CreateGeographicCoordinateSystem(4490); geometryDefEdit.SpatialReference_2 = pcsSys; IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; //将传入字段 转成 validatedFields fieldChecker.ValidateWorkspace = (IWorkspace)pFeatureWorkSpace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); /* field = new FieldClass(); IFieldsEdit pFieldsEdit = (IFieldsEdit)fields; IFieldEdit pFieldEdit = (IFieldEdit)field; pFieldEdit = (IFieldEdit)field; pFieldEdit.Name_2 = "面积"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; pFieldsEdit.AddField(field);*/ IArea s = pPolygon as IArea; double area = Math.Abs(s.Area * 10000); double length = Math.Abs(pPolygon.Length * 100); MessageBox.Show("该区域面积为:" + Convert.ToDouble(area).ToString("0.000") + "平方公里(km2)" + "\r\n" + "边长为:" + Convert.ToDouble(length).ToString("0.000") + "千米(KM)"); try { IFeatureClass pFeatureClass; pFeatureClass = pFeatureWorkSpace.CreateFeatureClass(shpname, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); IFeature pFeature = pFeatureClass.CreateFeature(); pFeature.Shape = pPolygon; //pFeature.set_Value(pFeature.Fields.FindField("面积"), area); pFeature.Store(); } catch(Exception ex) { MessageBox.Show(ex.Message); } }
public void insert(Transaction current, SEE see, ISpatialReference utmSR) { // Create table on datastore PGDB first? current.TxId = see.RestID; IPolygon sourcePolygon = see.Shape; //sourcePolygon.Project(utmSR); IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; fieldsEdit.FieldCount_2 = 3; //Create the Object ID field. IField fieldUserDefined = new Field(); IFieldEdit fieldEdit = (IFieldEdit)fieldUserDefined; fieldEdit.Name_2 = "OBJECTID"; fieldEdit.AliasName_2 = "OBJECT ID"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.set_Field(0, fieldUserDefined); // Create the Shape field. fieldUserDefined = new Field(); fieldEdit = (IFieldEdit)fieldUserDefined; // Set up the geometry definition for the Shape field. IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon; // By setting the grid size to 0, you're allowing ArcGIS to determine the appropriate grid sizes for the feature class. // If in a personal geodatabase, the grid size will be 1000. If in a file or ArcSDE geodatabase, the grid size // will be based on the initial loading or inserting of features. geometryDefEdit.GridCount_2 = 1; geometryDefEdit.set_GridSize(0, 0); geometryDefEdit.HasM_2 = false; geometryDefEdit.HasZ_2 = false; //Assign the spatial reference that was passed in, possibly from //IGeodatabase.SpatialReference for the containing feature dataset. if (see.Shape.SpatialReference != null) { geometryDefEdit.SpatialReference_2 = see.Shape.SpatialReference; } //if (utmSR == null) //{ // ISpatialReferenceFactory2 sre = (ISpatialReferenceFactory2)new SpatialReferenceEnvironment(); // utmSR = sre.CreateSpatialReference((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_10N); //} //geometryDefEdit.SpatialReference_2 = utmSR;// see.Shape.SpatialReference; // Set standard field properties. fieldEdit.Name_2 = "SHAPE"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; fieldEdit.GeometryDef_2 = geometryDef; fieldEdit.IsNullable_2 = true; fieldEdit.Required_2 = true; fieldsEdit.set_Field(1, fieldUserDefined); // Create a field of type double to hold some information for the features. fieldUserDefined = new Field(); fieldEdit = (IFieldEdit)fieldUserDefined; fieldEdit.Name_2 = "SPATIAL_EDIT_EXTENT_SP_ID"; fieldEdit.AliasName_2 = "SPATIAL_EDIT_EXTENT_SP_ID"; fieldEdit.Editable_2 = true; fieldEdit.IsNullable_2 = false; fieldEdit.Length_2 = 125; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(2, fieldUserDefined); // Create a feature class description object to use for specifying the CLSID and EXTCLSID. IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc; ESRI.ArcGIS.esriSystem.UID CLSID = new ESRI.ArcGIS.esriSystem.UIDClass(); // The enumFieldError enumerator can be inspected at this point to determine // which fields were modified during validation. IFeatureClass fc = osdb.CreateFeatureClass(OSDB_SEE_NAME, fields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDesc.ShapeFieldName, ""); //IGeoDatasetSchemaEdit fd_ed = (IGeoDatasetSchemaEdit)fc; //ISpatialReference oldSR = ((IGeoDataset)fc).SpatialReference; //if (fd_ed.CanAlterSpatialReference && !oldSR.Equals(utmSR)) //{ // // does not reproject the data // // doees alter all child feature classes // fd_ed.AlterSpatialReference(utmSR); //} IWorkspaceEdit wse = (IWorkspaceEdit)osdb; wse.StartEditing(false); wse.StartEditOperation(); try { fc = osdb.OpenFeatureClass(OSDB_SEE_NAME); } catch(Exception e) { MessageBox.Show("OSDB Feature Class " + OSDB_SEE_NAME + " Not Found in SUITT", "EXCEPTION", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new HandledException(e); } IFeatureCursor fcrs = null; try { fcrs = fc.Insert(false); IFeatureBuffer buffer = fc.CreateFeatureBuffer(); buffer.set_Value(fcrs.FindField(SEE_ID_COL), RestTransactionManager.Instance.NewTransactionSeeID); //buffer.set_Value(fcrs.FindField(OSDB_NAME_COL),current.OperationalDatasetName); //string t = current.Description; //if (t != null && t.Length > EDIT_INTENT_COL_LNG) //{ // t = t.Substring(0, EDIT_INTENT_COL_LNG); //} //buffer.set_Value(fcrs.FindField(EDIT_INTENT_COL), t); //buffer.set_Value(fcrs.FindField(OPEN_DATE_COL),current.CreationDate); //t = current.PGDB.FullName; //buffer.set_Value(fcrs.FindField(PGDB_PATH_COL), t); IPolygon p = sourcePolygon; if(p!=null) { //p.Project(utmSR); p.Project(((IGeoDataset)fc).SpatialReference); } buffer.Shape = p; fcrs.InsertFeature(buffer); fcrs.Flush(); // Explicitly release the cursor. Marshal.ReleaseComObject(fcrs); // Stop editing. wse.StopEditOperation(); wse.StopEditing(true); } catch(Exception e) { // Failed while writing the SEE area poygon to the PGDB? // We should carry on with the transaction, but the SEE area will be lost MessageBox.Show("Error occured storing SEE geometry. " + e.Message); } finally { if(fcrs != null) { Utils.Release(fcrs); } } }
private void CreateAndPopulateTurnFeatureClass(string outputFileGdbPath, string fdsName, string ProhibMPTableName, string tempStatsTableName, IGPMessages messages, ITrackCancel trackcancel) { // Determine the number of AltID fields we need (the same as the MAX_SEQNR value). Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory; var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace; ITable tempStatsTable = fws.OpenTable(tempStatsTableName); short numAltIDFields = 2; if (tempStatsTable.RowCount(null) == 1) numAltIDFields = (short)((double)(tempStatsTable.GetRow(1).get_Value(tempStatsTable.FindField("MAX_SEQNR")))); // Open the MP table and find the fields we need ITable mpTable = fws.OpenTable(ProhibMPTableName); int seqNrField = mpTable.FindField("SEQNR"); int trpElIDField = mpTable.FindField("TRPELID"); int idFieldOnMP = mpTable.FindField("ID"); int mpJnctIDField = mpTable.FindField("JNCTID"); // Create a temporary template feature class var fcd = new FeatureClassDescriptionClass() as IFeatureClassDescription; var ocd = fcd as IObjectClassDescription; var fieldsEdit = ocd.RequiredFields as IFieldsEdit; IField fieldOnMPTable = mpTable.Fields.get_Field(idFieldOnMP); // use the ID field as a template for the AltID fields for (short i = 1; i <= numAltIDFields; i++) { IFieldEdit newField = new FieldClass(); newField.Name_2 = "AltID" + i; newField.Precision_2 = fieldOnMPTable.Precision; newField.Scale_2 = fieldOnMPTable.Scale; newField.Type_2 = fieldOnMPTable.Type; fieldsEdit.AddField(newField as IField); } fieldsEdit.AddField(fieldOnMPTable); fieldOnMPTable = mpTable.Fields.get_Field(mpJnctIDField); fieldsEdit.AddField(fieldOnMPTable); var fieldChk = new FieldCheckerClass() as IFieldChecker; IEnumFieldError enumFieldErr = null; IFields validatedFields = null; fieldChk.ValidateWorkspace = fws as IWorkspace; fieldChk.Validate(fieldsEdit as IFields, out enumFieldErr, out validatedFields); var tempFC = fws.CreateFeatureClass("TheTemplate", validatedFields, ocd.InstanceCLSID, ocd.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcd.ShapeFieldName, "") as IDataset; // Create the turn feature class from the template, then delete the template Geoprocessor gp = new Geoprocessor(); CreateTurnFeatureClass createTurnFCTool = new CreateTurnFeatureClass(); string pathToFds = outputFileGdbPath + "\\" + fdsName; createTurnFCTool.out_location = pathToFds; createTurnFCTool.out_feature_class_name = TurnFCName; createTurnFCTool.maximum_edges = numAltIDFields; createTurnFCTool.in_template_feature_class = outputFileGdbPath + "\\TheTemplate"; gp.Execute(createTurnFCTool, trackcancel); tempFC.Delete(); // Open the new turn feature class and find all the fields on it IFeatureClass turnFC = fws.OpenFeatureClass(TurnFCName); int[] altIDFields = new int[numAltIDFields]; int[] edgeFCIDFields = new int[numAltIDFields]; int[] edgeFIDFields = new int[numAltIDFields]; int[] edgePosFields = new int[numAltIDFields]; for (short i = 0; i < numAltIDFields; i++) { altIDFields[i] = turnFC.FindField("AltID" + (i + 1)); edgeFCIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FCID"); edgeFIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FID"); edgePosFields[i] = turnFC.FindField("Edge" + (i + 1) + "Pos"); } int edge1endField = turnFC.FindField("Edge1End"); int idFieldOnTurnFC = turnFC.FindField("ID"); int turnFCJnctIDField = turnFC.FindField("JNCTID"); // Look up the FCID of the Streets feature class IFeatureClass streetsFC = fws.OpenFeatureClass(StreetsFCName); int streetsFCID = streetsFC.FeatureClassID; // Set up queries var ts = new TableSortClass() as ITableSort; ts.Fields = "ID, SEQNR"; ts.set_Ascending("ID", true); ts.set_Ascending("SEQNR", true); ts.QueryFilter = new QueryFilterClass(); ts.Table = mpTable; ts.Sort(null); ICursor mpCursor = ts.Rows; IFeatureCursor turnFCCursor = turnFC.Insert(true); IFeatureBuffer turnBuffer = turnFC.CreateFeatureBuffer(); // Write the field values to the turn feature class accordingly turnBuffer.set_Value(edge1endField, "?"); // dummy value; will be updated in a later calculation int numFeatures = 0; IRow mpRow = mpCursor.NextRow(); while (mpRow != null) { // Transfer the non-edge identifying field values to the buffer turnBuffer.set_Value(idFieldOnTurnFC, mpRow.get_Value(idFieldOnMP)); turnBuffer.set_Value(turnFCJnctIDField, mpRow.get_Value(mpJnctIDField)); // Write the AltID values to the buffer int seq = (int)(mpRow.get_Value(seqNrField)); int lastEntry; do { lastEntry = seq; turnBuffer.set_Value(altIDFields[lastEntry - 1], mpRow.get_Value(trpElIDField)); mpRow = mpCursor.NextRow(); if (mpRow == null) break; seq = (int)(mpRow.get_Value(seqNrField)); } while (seq != 1); // Zero-out the unused fields for (int i = lastEntry; i < numAltIDFields; i++) turnBuffer.set_Value(altIDFields[i], 0); // Write the FCID and Pos field values to the buffer for (short i = 0; i < numAltIDFields; i++) { double altID = (double)(turnBuffer.get_Value(altIDFields[i])); if (altID != 0) { turnBuffer.set_Value(edgeFCIDFields[i], streetsFCID); turnBuffer.set_Value(edgeFIDFields[i], 1); turnBuffer.set_Value(edgePosFields[i], 0.5); } else { turnBuffer.set_Value(edgeFCIDFields[i], 0); turnBuffer.set_Value(edgeFIDFields[i], 0); turnBuffer.set_Value(edgePosFields[i], 0); } } // Create the turn feature turnFCCursor.InsertFeature(turnBuffer); numFeatures++; if ((numFeatures % 100) == 0) { // check for user cancel if (trackcancel != null && !trackcancel.Continue()) throw (new COMException("Function cancelled.")); } } // Flush any outstanding writes to the turn feature class turnFCCursor.Flush(); // Update the Edge1End values AddMessage("Updating the Edge1End values...", messages, trackcancel); MakeFeatureLayer makeFeatureLayerTool = new MakeFeatureLayer(); makeFeatureLayerTool.in_features = pathToFds + "\\" + TurnFCName; makeFeatureLayerTool.out_layer = "Turn_Layer"; gp.Execute(makeFeatureLayerTool, trackcancel); AddJoin addJoinTool = new AddJoin(); addJoinTool.in_layer_or_view = "Turn_Layer"; addJoinTool.in_field = "AltID1"; addJoinTool.join_table = pathToFds + "\\" + StreetsFCName; addJoinTool.join_field = "ID"; gp.Execute(addJoinTool, trackcancel); CalculateField calcFieldTool = new CalculateField(); calcFieldTool.in_table = "Turn_Layer"; calcFieldTool.field = TurnFCName + ".Edge1End"; calcFieldTool.expression = "x"; calcFieldTool.code_block = "Select Case [" + TurnFCName + ".JNCTID]\n Case [" + StreetsFCName + ".F_JNCTID]: x = \"N\"\n Case [" + StreetsFCName + ".T_JNCTID]: x = \"Y\"\n Case Else: x = \"?\"\nEnd Select"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); RemoveJoin removeJoinTool = new RemoveJoin(); removeJoinTool.in_layer_or_view = "Turn_Layer"; removeJoinTool.join_name = StreetsFCName; gp.Execute(removeJoinTool, trackcancel); Delete deleteTool = new Delete(); deleteTool.in_data = "Turn_Layer"; gp.Execute(deleteTool, trackcancel); AddMessage("Updating the EdgeFID values...", messages, trackcancel); // Create a temporary network dataset for updating the EdgeFID values IDENetworkDataset dends = new DENetworkDatasetClass(); dends.SupportsTurns = true; dends.Buildable = true; (dends as IDataElement).Name = StreetsFCName; (dends as IDEGeoDataset).SpatialReference = (streetsFC as IGeoDataset).SpatialReference; IArray sourceArray = new ArrayClass(); var efs = new EdgeFeatureSourceClass() as IEdgeFeatureSource; (efs as INetworkSource).Name = StreetsFCName; efs.UsesSubtypes = false; efs.ClassConnectivityGroup = 1; efs.ClassConnectivityPolicy = esriNetworkEdgeConnectivityPolicy.esriNECPEndVertex; sourceArray.Add(efs); var tfs = new TurnFeatureSourceClass() as INetworkSource; tfs.Name = TurnFCName; sourceArray.Add(tfs); dends.Sources = sourceArray; var fdxc = fws.OpenFeatureDataset(fdsName) as IFeatureDatasetExtensionContainer; var dsCont = fdxc.FindExtension(esriDatasetType.esriDTNetworkDataset) as IDatasetContainer2; var tempNDS = dsCont.CreateDataset(dends as IDEDataset) as IDataset; // Set the EdgeFID field values by running UpdateByAlternateIDFields UpdateByAlternateIDFields updateByAltIDTool = new UpdateByAlternateIDFields(); updateByAltIDTool.in_network_dataset = pathToFds + "\\" + StreetsFCName; updateByAltIDTool.alternate_ID_field_name = "ID"; gp.Execute(updateByAltIDTool, trackcancel); // Delete the temporary network dataset tempNDS.Delete(); // Write the turn geometries TurnGeometryUtilities.WriteTurnGeometry(outputFileGdbPath, StreetsFCName, TurnFCName, numAltIDFields, 0.3, messages, trackcancel); // Index the turn geometries AddMessage("Creating spatial index on the turn feature class...", messages, trackcancel); AddSpatialIndex addSpatialIndexTool = new AddSpatialIndex(); addSpatialIndexTool.in_features = pathToFds + "\\" + TurnFCName; gp.Execute(addSpatialIndexTool, trackcancel); return; }
//coordinate 点坐标创建shp图层。 public static void CreatePolygonFeatureclass(IPolygon pPolygon, string shpfolder, string shpname) { IWorkspaceFactory pWorkSpaceFac = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWorkSpace = pWorkSpaceFac.OpenFromFile(shpfolder, 0) as IFeatureWorkspace; try {//如果图层存在则删除 FileInfo fFile = new FileInfo(shpfolder + @"\" + shpname+ ".shp");// if (fFile.Exists) { if (MessageBox.Show("此文件名已经存在,要覆盖吗?", "覆盖文件", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) { DirectoryInfo fold = new DirectoryInfo(shpfolder); FileInfo[] files = fold.GetFiles(shpname + ".*"); foreach (FileInfo f in files) { f.Delete(); } } else return; } } catch (Exception ex) { MessageBox.Show(ex.Message); } //if (File.Exists(shpfolder+shpname))//如果shp存在则替换它。 //{ // if (MessageBox.Show("发现同名文件,是否覆盖源文件?", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) // { // IFeatureClass featureclass = pFeatureWorkSpace.OpenFeatureClass(shpname); // IDataset pDataset = featureclass as IDataset; // pDataset.Delete(); // } // else // return; //} //创建字段集2 IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;//创建必要字段 IFields fields = ocDescription.RequiredFields; int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; //geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; //geometryDefEdit.SpatialReference_2 = spatialReference; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass(); // IProjectedCoordinateSystem pcsSys = pSpatialRefFac.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_Zone_39); IGeographicCoordinateSystem pcsSys = pSpatialRefFac.CreateGeographicCoordinateSystem(4490); geometryDefEdit.SpatialReference_2 = pcsSys; IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; //将传入字段 转成 validatedFields fieldChecker.ValidateWorkspace = (IWorkspace)pFeatureWorkSpace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); field = new FieldClass(); IFieldsEdit pFieldsEdit = (IFieldsEdit)fields; IFieldEdit pFieldEdit = (IFieldEdit)field; pFieldEdit = (IFieldEdit)field; pFieldEdit.Name_2 = "面积"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; pFieldsEdit.AddField(field); IArea s = pPolygon as IArea; double area = s.Area*100; double length=pPolygon.Length*100; MessageBox.Show("该区域面积为:" + Convert.ToDouble(area).ToString("0.000") + "平方公里(km2)" +"\r\n" + "边长为:" + Convert.ToDouble(length).ToString("0.000") + "千米(KM)"); try { IFeatureClass pFeatureClass; //pFeatureClass = pFeatureWorkSpace.OpenFeatureClass(shpname); pFeatureClass = pFeatureWorkSpace.CreateFeatureClass(shpname, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); IFeature pFeature = pFeatureClass.CreateFeature(); pFeature.Shape = pPolygon; // pFeature.set_Value(pFeature.Fields.FindField("面积"), area); pFeature.Store(); } catch { // MessageBox.Show("存储失败!请检查目录下是否有同名文件···", "提示"); //return; } }
public static IFields CreateFields(esriGeometryType geoType) { IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; IFields fields = ocDescription.RequiredFields; int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = geoType; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); var sr = spatialReferenceFactory.CreateGeographicCoordinateSystem(4326); geometryDefEdit.SpatialReference_2 = sr; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; field = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Name"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.AddField(field); return fields; }
/// <summary> /// 创建多边形shp /// </summary> /// <param name="pPolygon"></param> /// <param name="shpPath"></param> public static void CreatePolygonFeatureClass(IPolygon pPolygon, string shpfolder, string shpname) { IWorkspaceFactory pWorkSpaceFac = new ShapefileWorkspaceFactoryClass(); IWorkspaceEdit pWorkspaceEdit = (IWorkspaceEdit)pWorkSpaceFac; IFeatureWorkspace pFeatureWorkSpace = pWorkSpaceFac.OpenFromFile(shpfolder, 0) as IFeatureWorkspace; //创建字段集2 IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;//创建必要字段 IFields fields = ocDescription.RequiredFields; int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; //geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; //geometryDefEdit.SpatialReference_2 = spatialReference; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass(); IProjectedCoordinateSystem pcsSys = pSpatialRefFac.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_Zone_39); geometryDefEdit.SpatialReference_2 = pcsSys; IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; //将传入字段 转成 validatedFields fieldChecker.ValidateWorkspace = (IWorkspace)pFeatureWorkSpace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); field = new FieldClass(); IFieldsEdit pFieldsEdit = (IFieldsEdit)fields; IFieldEdit pFieldEdit = (IFieldEdit)field; pFieldEdit = (IFieldEdit)field; pFieldEdit.Name_2 = "面积"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; pFieldsEdit.AddField(field); pWorkspaceEdit.StartEditOperation(); IFeatureClass pFeatureClass = pFeatureWorkSpace.CreateFeatureClass(shpname, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); pPolygon = new PolygonClass(); IArea s = pPolygon as IArea; double area = s.Area; IFeature pfeature = pFeatureClass.CreateFeature(); pfeature.Shape = pPolygon; try { pfeature.set_Value(pfeature.Fields.FindField("面积"), area.ToString()); pfeature.Store(); } catch { MessageBox.Show(area.ToString()); } pWorkspaceEdit.StopEditOperation(); }
/// <summary> /// �����ֶμ��� /// </summary> /// <param name="ocDescription">Ҫ��������</param> /// <param name="tableStructureNode">��ṹ�ڵ�</param> /// <returns></returns> private IFields CreateFileds(TableStructureNode tableStructureNode, FeatureCodeNode featureCodeNode) { try { ///�����ֶμ��� IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = new ObjectClassDescriptionClass(); IFields fields = ocDescription.RequiredFields; //�������ļ���ȡͼ������ string sGeometryType = ""; Metadata.MetaTable pMetaTalbe = Metadata.MetaDataFile.MetaTabls[tableStructureNode.TableName] as Metadata.MetaTable; if (pMetaTalbe != null) { sGeometryType = Metadata.MetaDataFile.GraphConfig.GetGraphTypeMark(pMetaTalbe.Type); } //����ͼ������ if (sGeometryType != "NoneGeometry") { ocDescription = (IObjectClassDescription)fcDescription; fields = ocDescription.RequiredFields; int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField pGeometryfield = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = pGeometryfield.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; if (sGeometryType == "Point") geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; else if (sGeometryType == "Line") geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; else if (sGeometryType == "Polygon") geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; } IFieldsEdit fieldsEdit = fields as IFieldsEdit; // ������ṹ���� int FieldCount = tableStructureNode.FieldNodes.Count; for (int i = 0; i < FieldCount; i++) { IField field = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)field; ///��ȡ�ֶ���Ϣ FieldNode pFieldNode = tableStructureNode.FieldNodes[i]; if (pFieldNode != null) { ///�����ֶ�ֵ fieldEdit.Name_2 = pFieldNode.FieldName; //�������л�ȡ���� if (pMetaTalbe != null) fieldEdit.AliasName_2 = pMetaTalbe.GetFiledALisNameByCode(pFieldNode.FieldName); esriFieldType type = esriFieldType.esriFieldTypeString; switch (pFieldNode.FieldType) { case "Char": type = esriFieldType.esriFieldTypeString; break; case "Int": type = esriFieldType.esriFieldTypeInteger; break; case "Float": type = esriFieldType.esriFieldTypeDouble; break; case "Time": type = esriFieldType.esriFieldTypeDate; break; case "DateTime": type = esriFieldType.esriFieldTypeDate; break; case "Varchar": type = esriFieldType.esriFieldTypeString; break; case "Varbin": type = esriFieldType.esriFieldTypeString; break; default: break; } fieldEdit.Type_2 = type; fieldEdit.Length_2 = pFieldNode.FieldLength; fieldEdit.Precision_2 = pFieldNode.FieldPrecision; fieldsEdit.AddField(field); } } return fields; } catch(Exception ex) { LogAPI.WriteErrorLog(ex); return null; } }
private static IFields CreateGdbFields() { IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass(); // create the required fields IFields fields = objectClassDescription.RequiredFields; var fieldsEdit = (IFieldsEdit)fields; IFieldEdit fieldEdit = new FieldClass(); fieldEdit.Name_2 = "Col"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; fieldEdit.AliasName_2 = "Column"; fieldsEdit.AddField(fieldEdit); // ReSharper disable UseObjectOrCollectionInitializer // The field class COM object does not support object initializers fieldEdit = new FieldClass(); fieldEdit.Name_2 = "Row"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(fieldEdit); fieldEdit = new FieldClass(); fieldEdit.Name_2 = "Col_Label"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.AliasName_2 = "Column Label"; fieldEdit.Length_2 = 20; fieldsEdit.AddField(fieldEdit); fieldEdit = new FieldClass(); fieldEdit.Name_2 = "Row_Label"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.AliasName_2 = "Row Label"; fieldEdit.Length_2 = 20; fieldsEdit.AddField(fieldEdit); fieldEdit = new FieldClass(); fieldEdit.Name_2 = "Cell_Label"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.AliasName_2 = "Cell Label"; fieldEdit.Length_2 = 20; fieldsEdit.AddField(fieldEdit); fieldEdit = new FieldClass(); fieldEdit.Name_2 = "Page"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; fieldEdit.AliasName_2 = "Page Number"; fieldsEdit.AddField(fieldEdit); // ReSharper restore UseObjectOrCollectionInitializer return fields; }
private IFeatureClass CreateFeatureClass(IFeatureDataset featureDataset,TableStructureNode tableStructureNode, FeatureCodeNode featureCodeNode) { try { if (featureDataset != null) { IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc; ///�������ݱ��ֶ� IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = CreateFileds(tableStructureNode, featureCodeNode); ///�ֶ���Ϣ��֤ IFields fixFields = null; fieldChecker.ValidateWorkspace = featureDataset.Workspace; fieldChecker.Validate(validatedFields, out enumFieldError, out fixFields); ////����FeatureClass IFeatureClass featureClass = null; if (tableStructureNode.IsGeometryTable) { ////������ע��FeatureClass if (featureCodeNode.GeometryType != "") { featureClass = featureDataset.CreateFeatureClass(featureCodeNode.TableName, fixFields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDesc.ShapeFieldName, ""); } else { ///����ע�� IFormattedTextSymbol pTxtSymbo=new TextSymbolClass(); IFeatureWorkspaceAnno pFeatureWorkspaceAnno = this.m_pIDataset.Workspace as IFeatureWorkspaceAnno; IGraphicsLayerScale pGraphSacle = new GraphicsLayerScaleClass(); pGraphSacle.Units = ESRI.ArcGIS.esriSystem.esriUnits.esriFeet; //pGraphSacle.ReferenceScale=1000; ISymbolCollection pSymbolCollection = new SymbolCollectionClass(); IAnnotateLayerProperties pAnnoLayerProp = new LabelEngineLayerPropertiesClass(); pAnnoLayerProp.FeatureLinked = true; pAnnoLayerProp.CreateUnplacedElements = false; pAnnoLayerProp.DisplayAnnotation = true; pAnnoLayerProp.UseOutput = true; IAnnotationExpressionEngine pAnnoExpressionEngine =new AnnotationVBScriptEngineClass(); ILabelEngineLayerProperties pLabelEngineLayerProperties = pAnnoLayerProp as ILabelEngineLayerProperties; pLabelEngineLayerProperties.ExpressionParser = pAnnoExpressionEngine; pLabelEngineLayerProperties.Expression = "[DESCRIPTION]"; pLabelEngineLayerProperties.IsExpressionSimple = true; pLabelEngineLayerProperties.Offset = 0; pLabelEngineLayerProperties.SymbolID = 0; pLabelEngineLayerProperties.Symbol = pTxtSymbo; IAnnotateLayerTransformationProperties pAnnoLayerTransProp = pAnnoLayerProp as IAnnotateLayerTransformationProperties; pAnnoLayerTransProp.ReferenceScale=200; pAnnoLayerTransProp.Units= ESRI.ArcGIS.esriSystem.esriUnits.esriFeet; pAnnoLayerTransProp.ScaleRatio=1; IAnnotateLayerPropertiesCollection pAnnoLayerProptyCollection =new AnnotateLayerPropertiesCollectionClass(); pAnnoLayerProptyCollection.Add(pAnnoLayerProp); featureClass= pFeatureWorkspaceAnno.CreateAnnotationClass(featureCodeNode.TableName,fixFields,ocDesc.InstanceCLSID ,ocDesc.ClassExtensionCLSID,fcDesc.ShapeFieldName,"",featureDataset,null, pAnnoLayerProptyCollection, pGraphSacle, pSymbolCollection,true); } } else { ///�����ǿռ����� } return featureClass; } return null; } catch(Exception ex) { LogAPI.WriteErrorLog(ex); return null; } }
public void MakeScratchPoints() { try { IMxDocument pmxdoc = ArcMap.Document as IMxDocument; IMap pmap = pmxdoc.FocusMap; ILayer pShorePoints = FindLayer(pmap, "ShorePoints"); if (pShorePoints != null) { pmap.DeleteLayer(pShorePoints); } IScratchWorkspaceFactory workspaceFactory = new FileGDBScratchWorkspaceFactoryClass(); IScratchWorkspaceFactory2 workspaceFactory2 = workspaceFactory as IScratchWorkspaceFactory2; IWorkspace scratchWorkspace = workspaceFactory2.CreateNewScratchWorkspace(); IFeatureWorkspace pFeatWorkspace = scratchWorkspace as IFeatureWorkspace; // This function creates a new feature class in a supplied feature dataset by building all of the // fields from scratch. IFeatureClassDescription (or IObjectClassDescription if the table is // created at the workspace level) can be used to get the required fields and are used to // get the InstanceClassID and ExtensionClassID. // Create new fields collection with the number of fields you plan to add. Must add at least two fields // for a feature class: Object ID and Shape field. IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; fieldsEdit.FieldCount_2 = 3; // Create Object ID field. IField fieldUserDefined = new Field(); IFieldEdit fieldEdit = (IFieldEdit)fieldUserDefined; fieldEdit.Name_2 = "OBJECTID"; fieldEdit.AliasName_2 = "OBJECT ID"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.set_Field(0, fieldUserDefined); // Create Shape field. fieldUserDefined = new Field(); fieldEdit = (IFieldEdit)fieldUserDefined; // Set up geometry definition for the Shape field. // You do not have to set the spatial reference, as it is inherited from the feature dataset. IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint; geometryDefEdit.SpatialReference_2 = pmap.SpatialReference; // By setting the grid size to 0, you are allowing ArcGIS to determine the appropriate grid sizes for the feature class. // If in a personal geodatabase, the grid size is 1,000. If in a file or ArcSDE geodatabase, the grid size // is based on the initial loading or inserting of features. geometryDefEdit.GridCount_2 = 1; geometryDefEdit.set_GridSize(0, 0); geometryDefEdit.HasM_2 = false; geometryDefEdit.HasZ_2 = false; // Set standard field properties. fieldEdit.Name_2 = "SHAPE"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; fieldEdit.GeometryDef_2 = geometryDef; fieldEdit.IsNullable_2 = true; fieldEdit.Required_2 = true; fieldsEdit.set_Field(1, fieldUserDefined); // Create a field of type double to hold some information for the features. fieldUserDefined = new Field(); fieldEdit = (IFieldEdit)fieldUserDefined; fieldEdit.Name_2 = "ID"; fieldEdit.AliasName_2 = "ID"; fieldEdit.Editable_2 = true; fieldEdit.IsNullable_2 = false; fieldEdit.Precision_2 = 2; fieldEdit.Scale_2 = 5; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.set_Field(2, fieldUserDefined); // Create a feature class description object to use for specifying the CLSID and EXTCLSID. IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc; IFeatureClass pLineFClass = pFeatWorkspace.CreateFeatureClass("ShorePoints", fields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "SHAPE", ""); IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pLineFClass; pFeatureLayer.Name = "ShorePoints"; pmxdoc.AddLayer(pFeatureLayer); } catch (Exception ex) { MessageBox.Show(ex.Message); MessageBox.Show(ex.StackTrace); } }
/// <summary>Create a ESRI shapefile </summary> /// <param name="shapeFilePath">the path to the shapefile</param> /// <param name="field2add">List of Ifields</param> /// <param name="srs">the srs of the shapefile</param> /// <param name="geomType">the type geometry: point, polyline, polygon, ...</param> /// <param name="deleteIfExists">Overwrite existing FeatureClass</param> /// <returns>the shapefile loaded in a IFeatureClass</returns> public static IFeatureClass createShapeFile(string shapeFilePath, List<IField> field2add , ISpatialReference srs, esriGeometryType geomType, bool deleteIfExists = true) { FileInfo shapeInfo = new FileInfo(shapeFilePath); // Instantiate a feature class description to get the required fields. IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = fcDescription as IObjectClassDescription; IFields fields = ocDescription.RequiredFields; IFieldsEdit fieldsEdit = fields as IFieldsEdit; // Find the shape field in the required fields and modify its GeometryDef to // use wanted geometry and to set the spatial reference. int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField geofield = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = geofield.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = geomType; geometryDefEdit.SpatialReference_2 = srs; foreach (IField field in field2add) { fieldsEdit.AddField(field); } IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile( shapeInfo.DirectoryName , 0); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace) workspace; // Explict Cast if ( shapeInfo.Exists ) { if (deleteIfExists) { if (!deleteFeatureClass(shapeInfo.FullName)) { throw new Exception(shapeInfo.Name + " exists and cannot be deleted"); } } else { throw new Exception(shapeInfo.Name + " exists"); } } IFields validatedFields = validateFields((IWorkspace)workspace, fields); IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(shapeInfo.Name, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); return featureClass; }