//用帮助里的例子,修改了字段和空间参考
        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);
        }
示例#2
0
        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);
        }
示例#3
0
        public static ITable CreateObjectClass(IWorkspace workspace, String className, IFields fields)
        {
            IFeatureWorkspace       featureWorkspace = (IFeatureWorkspace)workspace;
            IObjectClassDescription ocDescription    = new ObjectClassDescriptionClass();

            // 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);

            // The enumFieldError enumerator can be inspected at this point to determine
            // which fields were modified during validation.
            ITable table = featureWorkspace.CreateTable(className, validatedFields,
                                                        ocDescription.InstanceCLSID, null, "");

            return(table);
        }
示例#4
0
        private IFeatureClass CopyFeatureClassIntoNewWorkspace(IFeatureClass inFeatureClass, IWorkspace outWorkspace,
                                                               string newName)
        {
            // get FeatureClassName for input
            var inDataset          = inFeatureClass as IDataset;
            var inFeatureClassName = inDataset.FullName as IFeatureClassName;
            var inWorkspace        = inDataset.Workspace;

            // get WorkSpaceName for output
            var outDataset       = outWorkspace as IDataset;
            var outWorkspaceName = outDataset.FullName as IWorkspaceName;

            // Create new FeatureClassName
            IFeatureClassName outFeatureClassName = new FeatureClassNameClass();
            // Assign it a name and a workspace
            var datasetName = outFeatureClassName as IDatasetName;

            datasetName.Name          = newName == String.Empty ? (inFeatureClassName as IDatasetName).Name : newName;
            datasetName.WorkspaceName = outWorkspaceName;

            // Check for field conflicts.
            IFieldChecker   fieldChecker = new FieldCheckerClass();
            IFields         inFields     = inFeatureClass.Fields;
            IFields         outFields;
            IEnumFieldError enumFieldError;

            fieldChecker.InputWorkspace    = inWorkspace;
            fieldChecker.ValidateWorkspace = outWorkspace;
            fieldChecker.Validate(inFields, out enumFieldError, out outFields);
            // Check enumFieldError for field naming conflicts

            //Convert the data.
            IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass();

            featureDataConverter.ConvertFeatureClass(inFeatureClassName, null, null,
                                                     outFeatureClassName, null, outFields, "", 100, 0);

            var pFeatureWS = (IFeatureWorkspace)outWorkspace;

            return(pFeatureWS.OpenFeatureClass(newName));
        }
示例#5
0
        protected IFields CloneFields(IWorkspace sourceWorkspace, IFeatureClass sourceFeatureClass, IWorkspace targetWorkspace)
        {
            // Create the objects and references necessary for field validation.
            IFieldChecker   fieldChecker   = new FieldCheckerClass();
            IFields         sourceFields   = sourceFeatureClass.Fields;
            IFields         targetFields   = null;
            IEnumFieldError enumFieldError = null;

            // Set the required properties for the IFieldChecker interface.
            fieldChecker.InputWorkspace    = sourceWorkspace;
            fieldChecker.ValidateWorkspace = targetWorkspace;

            // Validate the fields and check for errors.
            fieldChecker.Validate(sourceFields, out enumFieldError, out targetFields);
            if (enumFieldError != null)
            {
                // Handle the errors in a way appropriate to your application.
                throw new ArgumentException("Errors were encountered during field validation.");
            }
            return(targetFields);
        }
示例#6
0
        /// <summary>
        /// Exports the source table using the query filter to the table in the output workspace.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="filter">The filter.</param>
        /// <param name="tableName">Name of the output table.</param>
        /// <param name="workspace">The output workspace.</param>
        /// <param name="requiredFields">The required fields.</param>
        /// <param name="handle">The handle.</param>
        /// <param name="keepFeatureDatset">if set to <c>true</c> when the feature class should be created within feature datset.</param>
        /// <param name="surrogate">The surrogate for the event handler.</param>
        /// <param name="invalid">The errors that occured during the export.</param>
        /// <param name="errors">The field errors.</param>
        /// <returns>
        /// Returns a <see cref="IFeatureClass" /> representing the feature class that was exported.
        /// </returns>
        public static IFeatureClass Export(this IFeatureClass source, IQueryFilter filter, string tableName, IWorkspace workspace, IFields requiredFields, int handle, bool keepFeatureDatset, FeatureProgress surrogate, out IEnumInvalidObject invalid, out IEnumFieldError errors)
        {
            var ds = (IDataset)source;

            var input  = ds.Workspace.Define(ds.Name, new FeatureClassNameClass());
            var output = workspace.Define(tableName, new FeatureClassNameClass());

            if (source.FeatureDataset != null && keepFeatureDatset)
            {
                output.FeatureDatasetName = source.FeatureDataset.FullName as IDatasetName;
            }

            var i           = source.Fields.FindField(source.ShapeFieldName);
            var field       = source.Fields.Field[i];
            var clone       = (IClone)field.GeometryDef;
            var geometryDef = (IGeometryDef)clone.Clone();

            workspace.Delete(output);

            IFieldChecker fieldChecker = new FieldCheckerClass();

            fieldChecker.InputWorkspace    = ds.Workspace;
            fieldChecker.ValidateWorkspace = workspace;

            IFields targetFields;

            fieldChecker.Validate(requiredFields, out errors, out targetFields);

            var featureDataConverter = new FeatureDataConverterClass();

            if (surrogate != null)
            {
                surrogate.Advise(featureDataConverter);
            }

            invalid = featureDataConverter.ConvertFeatureClass(input, filter, null, output, geometryDef, targetFields, "", 1000, handle);

            return(((IName)output).Open() as IFeatureClass);
        }
        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);
        }
示例#8
0
        // create table in file geodatabase

        #region "create table in file geodatabase"

        public static ITable CreateTable(string tableName, UID classExtensionUID, IFeatureWorkspace featureWorkspace)
        {
            IFields fields = null;

            switch (tableName)
            {
            case "AtlNamesAddrPnts":
                fields = commands.CreateFieldsCollectionAddrPntsCommand.Execute();
                break;

            case "AtlNamesRoads":
                fields = commands.CreateFieldsCollectionRoadsCommand.Execute();;
                break;

            case "RoadsScratchData":
                fields = commands.CreateFieldsCollectionRoadsCommand.Execute();;
                break;

            default:
                Console.WriteLine("Name for altnames table not provided.");
                break;
            }

            // 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);

            // 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).
            var arcTable = featureWorkspace.CreateTable(tableName, validatedFields, null, classExtensionUID, "");

            return(arcTable);
        }
示例#9
0
        /// <summary>
        /// Creates fields for the Broadcast Feature Class.
        /// </summary>
        /// <param name="GDBWorkspace"></param>
        /// <param name="geoSpatRef"></param>
        /// <returns></returns>
        public static IFields createFeatureFields(IWorkspace GDBWorkspace, ISpatialReference geoSpatRef)
        {
            try
            {
                IFields     pFields     = new FieldsClass();
                IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;

                pFieldsEdit.AddField(createField("OID", esriFieldType.esriFieldTypeOID));

                pFieldsEdit.AddField(createShapeField(geoSpatRef, esriGeometryType.esriGeometryPoint));

                pFieldsEdit.AddField(createField("SOG", esriFieldType.esriFieldTypeInteger));
                pFieldsEdit.AddField(createField("COG", esriFieldType.esriFieldTypeInteger));
                pFieldsEdit.AddField(createField("Heading", esriFieldType.esriFieldTypeInteger));
                pFieldsEdit.AddField(createField("ROT", esriFieldType.esriFieldTypeInteger));
                pFieldsEdit.AddField(createField("BaseDateTime", esriFieldType.esriFieldTypeDate));
                pFieldsEdit.AddField(createField("Status", esriFieldType.esriFieldTypeInteger));
                pFieldsEdit.AddField(createField("VoyageID", esriFieldType.esriFieldTypeInteger));
                pFieldsEdit.AddField(createField("MMSI", esriFieldType.esriFieldTypeInteger));
                pFieldsEdit.AddField(createField("ReceiverType", esriFieldType.esriFieldTypeString));
                pFieldsEdit.AddField(createField("ReceiverID", esriFieldType.esriFieldTypeString));

                // Use IFieldChecker to create a validated fields collection.
                IFieldChecker   fieldChecker    = new FieldCheckerClass();
                IEnumFieldError enumFieldError  = null;
                IFields         validatedFields = null;
                fieldChecker.ValidateWorkspace = (IWorkspace)GDBWorkspace;
                fieldChecker.Validate(pFields, out enumFieldError, out validatedFields);

                return(pFields);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "AIS_Menu:Utilities:createFields");
                return(null);
            }
        }
示例#10
0
        /// <summary>
        /// Creates fields for the Voyage Tracks class.
        /// </summary>
        /// <param name="GDBWorkspace"></param>
        /// <returns></returns>
        private IFields CreateVoyageTrackFields(IWorkspace GDBWorkspace)
        {
            try
            {
                IFields     pFields     = new FieldsClass();
                IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;

                pFieldsEdit.AddField(clsStatic.CreateField("OID", esriFieldType.esriFieldTypeOID));

                pFieldsEdit.AddField(clsStatic.CreateShapeField(CreateGeographicSR(), esriGeometryType.esriGeometryPolyline));

                pFieldsEdit.AddField(clsStatic.CreateField("VoyageID", esriFieldType.esriFieldTypeInteger));
                pFieldsEdit.AddField(clsStatic.CreateField("Destination", esriFieldType.esriFieldTypeString));
                pFieldsEdit.AddField(clsStatic.CreateField("Cargo", esriFieldType.esriFieldTypeInteger));
                pFieldsEdit.AddField(clsStatic.CreateField("Draught", esriFieldType.esriFieldTypeInteger));
                pFieldsEdit.AddField(clsStatic.CreateField("ETA", esriFieldType.esriFieldTypeDate));
                pFieldsEdit.AddField(clsStatic.CreateField("StartTime", esriFieldType.esriFieldTypeDate));
                pFieldsEdit.AddField(clsStatic.CreateField("EndTime", esriFieldType.esriFieldTypeDate));
                pFieldsEdit.AddField(clsStatic.CreateField("MMSI", esriFieldType.esriFieldTypeInteger));
                pFieldsEdit.AddField(clsStatic.CreateField("SHAPE_Length", esriFieldType.esriFieldTypeInteger));

                // Use IFieldChecker to create a validated fields collection.
                IFieldChecker   fieldChecker    = new FieldCheckerClass();
                IEnumFieldError enumFieldError  = null;
                IFields         validatedFields = null;
                fieldChecker.ValidateWorkspace = (IWorkspace)GDBWorkspace;
                fieldChecker.Validate(pFields, out enumFieldError, out validatedFields);

                return(pFields);
            }
            catch (Exception ex)
            {
                clsStatic.ShowErrorMessage(ex.ToString());
                return(null);
            }
        }
示例#11
0
 /// <summary>
 /// 复制导入要素(ConvertFeatureDataset)
 /// </summary>
 /// <param name="pDataSet"></param>
 /// <param name="strFeatFileDir"></param>
 /// <param name="strFeatFileName"></param>
 /// <param name="strOutName"></param>
 /// <param name="isWorkspace"></param>
 public void FeatureClassToFeatureClass(IDataset pDataSet, string strFeatFileDir, string strFeatFileName, string strOutName, bool isWorkspace)
 {
     try
     {
         IWorkspaceFactory pWSF            = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass();
         IFeatureWorkspace pFeatureWK      = (IFeatureWorkspace)pWSF.OpenFromFile(strFeatFileDir, 0);
         IFeatureClass     pInFeatureClass = pFeatureWK.OpenFeatureClass(strFeatFileName);
         if (pInFeatureClass == null || pDataSet == null)
         {
             MessageBox.Show("创建失败");
             return;
         }
         IFeatureClassName pInFeatureclassName;
         IDataset          pIndataset = (IDataset)pInFeatureClass;
         pInFeatureclassName = (IFeatureClassName)pIndataset.FullName;
         //如果名称已存在
         IWorkspace2 pWS2 = null;
         if (isWorkspace)
         {
             pWS2 = pDataSet as IWorkspace2;
         }
         else
         {
             pWS2 = pDataSet.Workspace as IWorkspace2;
         }
         if (pWS2.get_NameExists(esriDatasetType.esriDTFeatureClass, strOutName))
         {
             MessageBoxResult result = MessageBox.Show(null, "矢量文件名  " + strOutName + "  在数据库中已存在!" + "/r是否覆盖?", "相同文件名", MessageBoxButton.YesNo, MessageBoxImage.Information, MessageBoxResult.Yes);
             //覆盖原矢量要素
             if (result == MessageBoxResult.Yes)
             {
                 IFeatureWorkspace pFWS     = (IFeatureWorkspace)pWS2;
                 IDataset          pDataset = pFWS.OpenFeatureClass(strOutName) as IDataset;
                 pDataset.Delete();
                 pDataset = null;
             }
         }
         IFields         pInFields, pOutFields;
         IFieldChecker   pFieldChecker = new FieldCheckerClass();
         IEnumFieldError pError;
         pInFields = pInFeatureClass.Fields;
         pFieldChecker.Validate(pInFields, out pError, out pOutFields);
         IField geoField = null;
         for (int i = 0; i < pOutFields.FieldCount; i++)
         {
             IField pField = pOutFields.get_Field(i);
             if (pField.Type == esriFieldType.esriFieldTypeOID)
             {
                 IFieldEdit pFieldEdit = (IFieldEdit)pField;
                 pFieldEdit.Name_2 = pField.AliasName;
             }
             if (pField.Type == esriFieldType.esriFieldTypeGeometry)
             {
                 geoField = pField;
                 break;
             }
         }
         IGeometryDef          geometryDef          = geoField.GeometryDef;
         IFeatureDataConverter one2another          = new FeatureDataConverterClass();
         IFeatureClassName     pOutFeatureClassName = new FeatureClassNameClass();
         IDatasetName          pOutDatasetName      = (IDatasetName)pOutFeatureClassName;
         if (isWorkspace)
         {
             pOutDatasetName.WorkspaceName = (IWorkspaceName)pDataSet.FullName;
         }
         else
         {
             pOutDatasetName.WorkspaceName = (IWorkspaceName)((IDataset)pDataSet.Workspace).FullName;
         }
         pOutDatasetName.Name = strOutName;
         if (isWorkspace)
         {
             one2another.ConvertFeatureClass(pInFeatureclassName, null, null, pOutFeatureClassName, geometryDef, pOutFields, "", 1000, 0);
         }
         else
         {
             IFeatureDataset     pFeatDS        = (IFeatureDataset)pDataSet;
             IFeatureDatasetName pOutFeatDSName = pFeatDS.FullName as IFeatureDatasetName;
             one2another.ConvertFeatureClass(pInFeatureclassName, null, pOutFeatDSName, pOutFeatureClassName, geometryDef, pOutFields, "", 1000, 0);
             pOutFeatDSName = null;
             pFeatDS        = null;
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
         return;
     }
 }
示例#12
0
        /// <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();
        }
示例#13
0
        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);

            }
        }
        /// <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;
        }
示例#15
0
        /// <summary>
        /// 转格式
        /// </summary>
        /// <param name="sourceWorkspacePath"></param>
        /// <param name="targetWorkspacePath"></param>
        /// <param name="sourceDataName"></param>
        /// <param name="targetDataName"></param>
        public static void ConvertFeatureClassToShapefile(string sourceWorkspacePath, string targetWorkspacePath, string sourceDataName, string targetDataName)
        {
            // Open the source and target workspaces.
              IWorkspaceFactory sourceWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
              IWorkspaceFactory targetWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
              IWorkspace sourceWorkspace = sourceWorkspaceFactory.OpenFromFile(sourceWorkspacePath, 0);
              IWorkspace targetWorkspace = targetWorkspaceFactory.OpenFromFile(targetWorkspacePath, 0);

              // Cast the workspaces to the IDataset interface and get name objects.
              IDataset sourceWorkspaceDataset = (IDataset)sourceWorkspace;
              IDataset targetWorkspaceDataset = (IDataset)targetWorkspace;
              IName sourceWorkspaceDatasetName = sourceWorkspaceDataset.FullName;
              IName targetWorkspaceDatasetName = targetWorkspaceDataset.FullName;
              IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDatasetName;
              IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDatasetName;

              // Create a name object for the shapefile and cast it to the IDatasetName interface.
              IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
              IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName;
              sourceDatasetName.Name = sourceDataName;//"streets";
              sourceDatasetName.WorkspaceName = sourceWorkspaceName;

              // Create a name object for the FGDB feature class and cast it to the IDatasetName interface.
              IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
              IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName;
              targetDatasetName.Name = targetDataName;// "AtlantaStreets";
              targetDatasetName.WorkspaceName = targetWorkspaceName;

              // Open source feature class to get field definitions.
              IName sourceName = (IName)sourceFeatureClassName;
              IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();

              // Create the objects and references necessary for field validation.
              IFieldChecker fieldChecker = new FieldCheckerClass();
              IFields sourceFields = sourceFeatureClass.Fields;
              IFields targetFields = null;
              IEnumFieldError enumFieldError = null;

              // Set the required properties for the IFieldChecker interface.
              fieldChecker.InputWorkspace = sourceWorkspace;
              fieldChecker.ValidateWorkspace = targetWorkspace;

              // Validate the fields and check for errors.
              fieldChecker.Validate(sourceFields, out enumFieldError, out targetFields);
              if (enumFieldError != null)
              {
            // Handle the errors in a way appropriate to your application.
            Console.WriteLine("Errors were encountered during field validation.");
              }

              // Find the shape field.
              String shapeFieldName = sourceFeatureClass.ShapeFieldName;
              int shapeFieldIndex = sourceFeatureClass.FindField(shapeFieldName);
              IField shapeField = sourceFields.get_Field(shapeFieldIndex);

              // Get the geometry definition from the shape field and clone it.
              IGeometryDef geometryDef = shapeField.GeometryDef;
              IClone geometryDefClone = (IClone)geometryDef;
              IClone targetGeometryDefClone = geometryDefClone.Clone();
              IGeometryDef targetGeometryDef = (IGeometryDef)targetGeometryDefClone;

              // Create a query filter to remove ramps, interstates and highways.
              IQueryFilter queryFilter = new QueryFilterClass();
              //queryFilter.WhereClause = "NAME <> 'Ramp' AND PRE_TYPE NOT IN ('I', 'Hwy')";
              queryFilter.WhereClause = "1=1";
              // Create the converter and run the conversion.
              IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass();
              IEnumInvalidObject enumInvalidObject =
            featureDataConverter.ConvertFeatureClass(sourceFeatureClassName,
            queryFilter, null, targetFeatureClassName, targetGeometryDef, targetFields,
            "", 1000, 0);

              // Check for errors.
              IInvalidObjectInfo invalidObjectInfo = null;
              enumInvalidObject.Reset();
              while ((invalidObjectInfo = enumInvalidObject.Next()) != null)
              {
            // Handle the errors in a way appropriate to the application.
            Console.WriteLine("Errors occurred for the following feature: {0}",
              invalidObjectInfo.InvalidObjectID);
              }
        }
示例#16
0
        //将mdb中要素类转换复制到GDB数据库中
        private void ImportMDBToGDB(string file, string outfilename)
        {
            m_success = false;//初始化
            try
            {
                string filepath = file.Substring(0, file.LastIndexOf("---"));
                string filename = file.Substring(file.LastIndexOf("-") + 1);

                //打开mdb文件所在的工作空间
                ESRI.ArcGIS.Geodatabase.IWorkspaceFactory wf = new AccessWorkspaceFactory();
                IFeatureWorkspace pFeatureWorkspaceMDB       = wf.OpenFromFile(@filepath, 0) as IFeatureWorkspace;
                IWorkspace        pWorkspaceMDB = pFeatureWorkspaceMDB as IWorkspace;
                // 创建源工作空间名称
                IDataset       sourceWorkspaceDataset = (IDataset)pWorkspaceMDB;
                IWorkspaceName sourceWorkspaceName    = (IWorkspaceName)sourceWorkspaceDataset.FullName;

                //创建源数据集名称
                //IFeatureClassName sourceFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName;
                IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
                IDatasetName      sourceDatasetName      = (IDatasetName)sourceFeatureClassName;
                sourceDatasetName.WorkspaceName = sourceWorkspaceName;
                sourceDatasetName.Name          = filename;

                //打开存在的工作空间,作为导入的空间
                IWorkspaceFactory Pwf = new FileGDBWorkspaceFactoryClass();
                //IWorkspace pWorkspaceGDB = Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0);
                //IWorkspace2 pWorkspace2 = (IWorkspace2)(Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0));
                IWorkspace pWorkspaceGDB = GetWorkspace(comboBoxSource.Text);
                if (pWorkspaceGDB == null)
                {
                    m_strErr  = "数据源未找到";
                    m_success = false;
                    return;
                }
                string username = GetSourceUser(comboBoxSource.Text);
                if (username.Trim() != "")
                {
                    outfilename = username + "." + outfilename;
                }
                IWorkspace2       pWorkspace2       = pWorkspaceGDB as IWorkspace2;
                IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceGDB;

                //创建目标工作空间名称
                IDataset       targetWorkspaceDataset = (IDataset)pWorkspaceGDB;
                IWorkspaceName targetWorkspaceName    = (IWorkspaceName)targetWorkspaceDataset.FullName;

                //创建目标数据集名称
                // IFeatureClassName targetFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName;
                //判断要素是否存在,若存在将删除源文件
                if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, outfilename))
                {
                    if (m_newfile == true)
                    {
                        IFeatureClass tmpfeatureclass;
                        tmpfeatureclass = pFeatureWorkspace.OpenFeatureClass(outfilename);
                        IDataset set = tmpfeatureclass as IDataset;
                        fdr.DeleteSql(filename);
                        set.CanDelete();
                        set.Delete();
                    }
                    else
                    {
                        m_strErr  = "存在相同文件名";
                        m_success = false;
                        return;
                    }
                }
                IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
                IDatasetName      targetDatasetName      = (IDatasetName)targetFeatureClassName;
                targetDatasetName.WorkspaceName = targetWorkspaceName;
                targetDatasetName.Name          = outfilename;

                //打开输入的要素类以得到字段定义
                ESRI.ArcGIS.esriSystem.IName sourceName = (ESRI.ArcGIS.esriSystem.IName)sourceFeatureClassName;
                IFeatureClass sourceFeatureClass        = (IFeatureClass)sourceName.Open();//打开源要素类

                //验证字段名称,因为你正在不同类型的工作空间之间进行数据转换
                //IFieldChecker fieldChecker = serverContext.CreateObject("esriGeoDatabase.FieldChecker") as IFieldChecker;
                IFieldChecker   fieldChecker             = new FieldCheckerClass();
                IFields         sourceFeatureClassFields = sourceFeatureClass.Fields;
                IFields         targetFeatureClassFields;
                IEnumFieldError enumFieldError;

                //最重要的设置输入和验证工作空间
                fieldChecker.InputWorkspace    = pWorkspaceMDB;
                fieldChecker.ValidateWorkspace = pWorkspaceGDB;
                fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);

                //遍历所有输出字段找到几何字段
                IField geometryField;
                for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
                {
                    if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        geometryField = targetFeatureClassFields.get_Field(i);
                        //得到几何字段的几何定义
                        IGeometryDef geometryDef = geometryField.GeometryDef;
                        //赋予几何定义一个空间索引格网数目和格网大小值
                        IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef;
                        targetFCGeoDefEdit.GridCount_2 = 1;
                        targetFCGeoDefEdit.set_GridSize(0, 0);
                        //允许ArcGIS为数据加载确定一个有效的格网大小
                        targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;
                        //转换要素类中所有的要素
                        //IQueryFilter queryFilter = serverContext.CreateObject("esriGeoDatabase.QueryFilter") as IQueryFilter; ;
                        QueryFilter queryFilter = new QueryFilterClass();
                        queryFilter.WhereClause = "";
                        //加载要素类
                        //IFeatureDataConverter fctofc = serverContext.CreateObject("esriGeoDatabase.FeatureDataConverter") as IFeatureDataConverter;
                        if (InsertIntoDatabase(outfilename))//更新数据库
                        {
                            IFeatureDataConverter fctofc     = new FeatureDataConverterClass();
                            IEnumInvalidObject    enumErrors = fctofc.ConvertFeatureClass(sourceFeatureClassName, queryFilter, null, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0);
                        }
                    }
                }
                m_success = true;
            }
            catch { m_success = false; m_strErr = ""; }
        }
示例#17
0
        public IFeatureClass CreateWithoutDescription(String featureClassName, UID classExtensionUID, IFeatureWorkspace featureWorkspace, esriGeometryType geoType, IFields fields)
        {
            // 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);

            IFeatureClass featureClass = featureWorkspace.CreateFeatureClass
                (featureClassName, validatedFields, null, classExtensionUID,
                esriFeatureType.esriFTSimple, "Shape", "");
            return featureClass;
        }
示例#18
0
        /// <summary>
        /// 拷贝源图层到空间数据集下的目标图层
        /// </summary>
        /// <param name="sourceWorkspace"></param>
        /// <param name="targetWorkspace"></param>
        /// <param name="nameOfSourceFeatureClass"></param>
        /// <param name="nameOfTargetFeatureClass"></param>
        public static void ConvertFeatureClass(IWorkspace sourceWorkspace, IWorkspace targetWorkspace,
                                               string nameOfSourceFeatureClass, string nameOfTargetFeatureClass)
        {
            try
            {
                //create source workspace name
                IDataset sourceWorkspaceDataset = (IDataset)sourceWorkspace;
                IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDataset.FullName;

                //create source dataset name
                IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();

                IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName;
                sourceDatasetName.WorkspaceName = sourceWorkspaceName;
                sourceDatasetName.Name = nameOfSourceFeatureClass;
                //create target workspace name
                IDataset targetWorkspaceDataset = (IDataset)targetWorkspace;
                IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDataset.FullName;
                //create target dataset name
                IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
                IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName;
                targetDatasetName.WorkspaceName = targetWorkspaceName;
                targetDatasetName.Name = nameOfTargetFeatureClass;
                //Open input Featureclass to get field definitions.
                IName sourceName = (IName)sourceFeatureClassName;
                IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();
                //Validate the field names because you are converting between different workspace types.
                IFieldChecker fieldChecker = new FieldCheckerClass();
                IFields targetFeatureClassFields;
                IFields sourceFeatureClassFields = sourceFeatureClass.Fields;
                IEnumFieldError enumFieldError;
                // Most importantly set the input and validate workspaces!
                fieldChecker.InputWorkspace = sourceWorkspace;
                fieldChecker.ValidateWorkspace = targetWorkspace;
                fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);
                // Loop through the output fields to find the geomerty field
                IField geometryField;
                for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
                {
                    geometryField = targetFeatureClassFields.get_Field(i);
                    if (geometryField.Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        // Get the geometry field's geometry defenition
                        IGeometryDef geometryDef = geometryField.GeometryDef;

                        //Give the geometry definition a spatial index grid count and grid size
                        IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef;

                        //targetFCGeoDefEdit.GridCount_2 = 1;
                        //targetFCGeoDefEdit.set_GridSize(0, 1000);
                        //Allow ArcGIS to determine a valid grid size for the data loaded
                        targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;
                        // we want to convert all of the features
                        IQueryFilter queryFilter = new QueryFilterClass();
                        queryFilter.WhereClause = "";

                        IEnumDataset pEnumDataset = targetWorkspace.get_Datasets(esriDatasetType.esriDTFeatureDataset);
                        IFeatureDataset ipDataset = (IFeatureDataset)pEnumDataset.Next();
                        IDatasetName pTargetDsName = (IDatasetName)ipDataset.FullName;
                        // Load the feature class
                        IFeatureDataConverter fctofc = new FeatureDataConverterClass();

                        IEnumInvalidObject enumErrors =
                            fctofc.ConvertFeatureClass(sourceFeatureClassName, queryFilter,
                                                       pTargetDsName as IFeatureDatasetName, targetFeatureClassName,
                                                       geometryDef, targetFeatureClassFields, "", 1000, 0);
                        IInvalidObjectInfo obj = enumErrors.Next();
                        break;
                    }
                }
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                return;
            }
        }
        public IFeatureClass exportFeatures(IFeatureClass inputFeatureClass, string outPath, ISpatialFilter filter)
        {
            // Create a name object for the source (shapefile) workspace and open it.
            IDataset inDset = (IDataset)inputFeatureClass;
            IWorkspace sourceWorkspace = (inDset).Workspace;

            // Create a name object for the target (file GDB) workspace and open it.
            string outDbStr = geoUtil.parseDbStr(outPath);
            string outName = System.IO.Path.GetFileName(outPath);
            IWorkspace targetWorkspace = geoUtil.OpenWorkSpace(outDbStr);
            outName = geoUtil.getSafeOutputNameNonRaster(targetWorkspace, outName);

            // Create a name object for the source dataset.
            IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
            IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName;
            sourceDatasetName.Name = inDset.Name;
            sourceDatasetName.WorkspaceName = (IWorkspaceName)((IDataset)sourceWorkspace).FullName;

            // Create a name object for the target dataset.
            IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
            IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName;
            targetDatasetName.Name = outName;
            targetDatasetName.WorkspaceName = (IWorkspaceName)((IDataset)targetWorkspace).FullName; ;

            // Open source feature class to get field definitions.
            //IName sourceName = (IName)sourceFeatureClassName;
            IFeatureClass sourceFeatureClass = inputFeatureClass;

            // Create the objects and references necessary for field validation.
            IFieldChecker fieldChecker = new FieldCheckerClass();
            IFields sourceFields = sourceFeatureClass.Fields;
            IFields targetFields = null;
            IEnumFieldError enumFieldError = null;

            // Set the required properties for the IFieldChecker interface.
            fieldChecker.InputWorkspace = sourceWorkspace;
            fieldChecker.ValidateWorkspace = targetWorkspace;

            // Validate the fields and check for errors.
            fieldChecker.Validate(sourceFields, out enumFieldError, out targetFields);
            if (enumFieldError != null)
            {
                // Handle the errors in a way appropriate to your application.
                Console.WriteLine("Errors were encountered during field validation.");
            }

            // Find the shape field.
            String shapeFieldName = sourceFeatureClass.ShapeFieldName;
            int shapeFieldIndex = sourceFeatureClass.FindField(shapeFieldName);
            IField shapeField = sourceFields.get_Field(shapeFieldIndex);

            // Get the geometry definition from the shape field and clone it.
            IGeometryDef geometryDef = shapeField.GeometryDef;
            IClone geometryDefClone = (IClone)geometryDef;
            IClone targetGeometryDefClone = geometryDefClone.Clone();
            IGeometryDef targetGeometryDef = (IGeometryDef)targetGeometryDefClone;

            // Cast the IGeometryDef to the IGeometryDefEdit interface.
            IGeometryDefEdit targetGeometryDefEdit = (IGeometryDefEdit)targetGeometryDef;

            // Set the IGeometryDefEdit properties.
            targetGeometryDefEdit.GridCount_2 = 1;
            targetGeometryDefEdit.set_GridSize(0, 0.75);

            // Create the converter and run the conversion.
            IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass();
            IEnumInvalidObject enumInvalidObject = featureDataConverter.ConvertFeatureClass(sourceFeatureClassName, filter, null, targetFeatureClassName, targetGeometryDef, targetFields, "", 1000, 0);

            // Check for errors.
            IInvalidObjectInfo invalidObjectInfo = null;
            enumInvalidObject.Reset();
            while ((invalidObjectInfo = enumInvalidObject.Next()) != null)
            {
                // Handle the errors in a way appropriate to the application.
                Console.WriteLine("Errors occurred for the following feature: {0}", invalidObjectInfo.InvalidObjectID);
            }
            return (IFeatureClass)((IName)targetFeatureClassName).Open();
        }
        public ITable exportTable(ITable inputTable, string outPath, IQueryFilter filter)
        {
            // Create a name object for the source workspace and open it.
            IDataset inDset = (IDataset)inputTable;
            IWorkspace sourceWorkspace = (inDset).Workspace;

            // Create a name object for the target (file GDB) workspace and open it.
            string outDbStr = geoUtil.parseDbStr(outPath);
            string outName = System.IO.Path.GetFileName(outPath);
            IWorkspace targetWorkspace = geoUtil.OpenWorkSpace(outDbStr);
            outName = geoUtil.getSafeOutputNameNonRaster(targetWorkspace, outName);

            // Create a name object for the source dataset.
            ITableName sourceTableName = new TableNameClass();
            IDatasetName sourceDatasetName = (IDatasetName)sourceTableName;
            sourceDatasetName.Name = inDset.Name;
            sourceDatasetName.WorkspaceName = (IWorkspaceName)((IDataset)sourceWorkspace).FullName;

            // Create a name object for the target dataset.
            ITableName targetTableName = new TableNameClass();
            IDatasetName targetDatasetName = (IDatasetName)targetTableName;
            targetDatasetName.Name = outName;
            targetDatasetName.WorkspaceName = (IWorkspaceName)((IDataset)targetWorkspace).FullName; ;

            // Open source feature class to get field definitions.
            //IName sourceName = (IName)sourceFeatureClassName;
            ITable sourceTable = inputTable;

            // Create the objects and references necessary for field validation.
            IFieldChecker fieldChecker = new FieldCheckerClass();
            IFields sourceFields = sourceTable.Fields;
            IFields targetFields = null;
            IEnumFieldError enumFieldError = null;

            // Set the required properties for the IFieldChecker interface.
            fieldChecker.InputWorkspace = sourceWorkspace;
            fieldChecker.ValidateWorkspace = targetWorkspace;

            // Validate the fields and check for errors.
            fieldChecker.Validate(sourceFields, out enumFieldError, out targetFields);
            if (enumFieldError != null)
            {
                // Handle the errors in a way appropriate to your application.
                Console.WriteLine("Errors were encountered during field validation.");
            }

            // Create the converter and run the conversion.
            IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass();
            IEnumInvalidObject enumInvalidObject = featureDataConverter.ConvertTable(sourceDatasetName, filter, targetDatasetName, targetFields,"",1000,0);

            // Check for errors.
            IInvalidObjectInfo invalidObjectInfo = null;
            enumInvalidObject.Reset();
            while ((invalidObjectInfo = enumInvalidObject.Next()) != null)
            {
                // Handle the errors in a way appropriate to the application.
                Console.WriteLine("Errors occurred for the following feature: {0}", invalidObjectInfo.InvalidObjectID);
            }
            return (Table)((IName)targetTableName).Open();
        }
        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;
        }
示例#22
0
        /// <summary>
        /// 创建要素图层
        /// 也可以利用现有要素图层创建:IFeatureLayer featurelayer,
        /// </summary>
        /// <param name="map"></param>
        /// <param name="workspace"></param>
        /// <param name="layername"></param>
        /// <param name="aliasname"></param>
        /// <returns></returns>
        public IFeatureLayer CreateFeatureLayer(IMap map, IWorkspace workspace,
                                                string layername, string aliasname)
        {
            try
            {
                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;
                //IFields fields = featurelayer.FeatureClass.Fields;

                // 创建要素类的字段集
                IFields     fields     = new FieldsClass();
                IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

                // 添加要素类必须字段:object ID 字段
                IField     oidField     = new FieldClass();
                IFieldEdit oidFieldEdit = (IFieldEdit)oidField;
                oidFieldEdit.Name_2 = "OBJECTID";
                oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
                fieldsEdit.AddField(oidField);

                // 创建几何定义(和空间参考)
                IGeometryDef     geometryDef     = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
                //ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                //ISpatialReference spatialReference =
                //spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_20N);
                //ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;
                //spatialReferenceResolution.ConstructFromHorizon();
                //ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;
                //spatialReferenceTolerance.SetDefaultXYTolerance();
                geometryDefEdit.SpatialReference_2 = map.SpatialReference;

                //添加几何字段
                IField     geometryField     = new FieldClass();
                IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField;
                geometryFieldEdit.Name_2        = "Shape";
                geometryFieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
                geometryFieldEdit.GeometryDef_2 = geometryDef;
                fieldsEdit.AddField(geometryField);

                //新建字段
                IField     pField     = new FieldClass();
                IFieldEdit pFieldEdit = pField as IFieldEdit;
                pFieldEdit.Length_2    = 50;
                pFieldEdit.Name_2      = "ID";
                pFieldEdit.AliasName_2 = "ID";
                pFieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                fieldsEdit.AddField(pField);

                //检查字段的有效性
                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(layername, validatedFields, null, null,
                                                                                 esriFeatureType.esriFTSimple, "Shape", "");

                //用创建的要素类生成要素图层
                IFeatureLayer newFeaLayer = new FeatureLayerClass();
                newFeaLayer.FeatureClass = featureClass;
                newFeaLayer.Name         = aliasname;

                //添加新建图层到相应图层组中
                IGroupLayer groupLayer     = new GroupLayerClass();
                string      groupLayerName = aliasname.Split("-".ToCharArray())[1].Trim();
                groupLayer = GetGroupLayerByName(groupLayerName);
                groupLayer.Add(newFeaLayer as ILayer);
                DataEditCommon.g_axTocControl.Update();
                DataEditCommon.g_pAxMapControl.Refresh();

                return(newFeaLayer);
            }
            catch (Exception ex)
            {
                Log.Debug(ex.ToString());
                return(null);
            }
        }
示例#23
0
        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)
            {
                Logger.WriteErrorLog(ex);
                return null;
            }
        }
示例#24
0
        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;
            }
        }
示例#25
0
        public void IFeatureDataConverter(IWorkspace pSourceWorkspace, IWorkspace pTargetWorkspace, string pSFeatureClass, string pDFeatureClass)
        {
            IDataset sourceWorkspaceDataset = (IDataset)pSourceWorkspace;
            IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDataset.FullName;

            IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
            IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName;
            sourceDatasetName.WorkspaceName = sourceWorkspaceName;
            sourceDatasetName.Name = pSFeatureClass;

            IDataset targetWorkspaceDataset = (IDataset)pTargetWorkspace;
            IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDataset.FullName;

            IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
            IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName;
            targetDatasetName.WorkspaceName = targetWorkspaceName;
            targetDatasetName.Name = pDFeatureClass;

            ESRI.ArcGIS.esriSystem.IName sourceName = (ESRI.ArcGIS.esriSystem.IName)sourceFeatureClassName;
            IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();

            IFieldChecker fieldChecker = new FieldCheckerClass();
            IFields targetFeatureClassFields;
            IFields sourceFeatureClassFields = sourceFeatureClass.Fields;
            IEnumFieldError enumFieldError;

            fieldChecker.InputWorkspace = pSourceWorkspace;
            fieldChecker.ValidateWorkspace = pTargetWorkspace;
            fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);

            IField geometryField;
            for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
            {
                if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                {
                    geometryField = targetFeatureClassFields.get_Field(i);

                    IGeometryDef geometryDef = geometryField.GeometryDef;

                    IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef;
                    targetFCGeoDefEdit.GridCount_2 = 1;
                    targetFCGeoDefEdit.set_GridSize(0, 0);

                    targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;

                    IQueryFilter queryFilter = new QueryFilterClass();
                    queryFilter.WhereClause = "";

                    IFeatureDataConverter fctofc = new FeatureDataConverterClass();
                    IEnumInvalidObject enumErrors = fctofc.ConvertFeatureClass(sourceFeatureClassName, queryFilter, null, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0);
                    break;
                }
            }
        }
示例#26
0
        /// <summary>
        /// �������Ա�
        /// </summary>
        /// <param name="pFeatureWorkspace"></param>
        /// <param name="tableStructureNode"></param>
        /// <param name="featureCodeNode"></param>
        /// <returns></returns>
        private TableLayer CreateTableLayer(IFeatureWorkspace pFeatureWorkspace, TableStructureNode tableStructureNode, FeatureCodeNode featureCodeNode)
        {
            try
            {
                if (pFeatureWorkspace != null&&tableStructureNode!=null&&featureCodeNode!=null)
                {
                    IObjectClassDescription ocDescription = new ObjectClassDescriptionClass();
                    ///�������ݱ��ֶ�
                    IFieldChecker fieldChecker = new FieldCheckerClass();
                    IFields validatedFields = CreateFileds(tableStructureNode, featureCodeNode);
                    ///�ֶ���Ϣ��֤
                    IFields fixFields = null;
                    fieldChecker.ValidateWorkspace = pFeatureWorkspace as IWorkspace;
                    IEnumFieldError enumFieldError = null;
                    fieldChecker.Validate(validatedFields, out enumFieldError, out fixFields);

                    ITable pTable = pFeatureWorkspace.CreateTable(tableStructureNode.TableName, fixFields,
                        ocDescription.InstanceCLSID, null, "");
                    if (pTable != null)
                    {
                        TableLayer pTableLayer = new TableLayer();

                        //�������ļ���ȡͼ������
                        string sGeometryType = "";
                        Metadata.MetaTable pMetaTalbe = Metadata.MetaDataFile.MetaTabls[tableStructureNode.TableName] as Metadata.MetaTable;
                        if (pMetaTalbe != null)
                        {
                            sGeometryType = pMetaTalbe.Type;
                        }
                        else
                            return null;

                        pTableLayer.GeometryType = sGeometryType;
                        pTableLayer.Table = pTable;
                        pTableLayer.UpdateFieldIndex();
                        return pTableLayer;
                    }
                    return null;
                }
                return null;
            }
            catch (Exception ex)
            {
                LogAPI.WriteErrorLog(ex);
                return null;
            }
        }
        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;
        }
        private void CreateRoadSplitsTable(string inputRdmsTable, string outputFileGdbPath, IGPMessages messages, ITrackCancel trackcancel)
        {
            // Open the Rdms table and find all the fields we need

            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
            var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory;
            var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace;
            ITable rdmsTable = fws.OpenTable(inputRdmsTable);
            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");

            // Open the Streets feature class and get its feature class ID

            IFeatureClass inputLineFeatures = fws.OpenFeatureClass(StreetsFCName);
            int streetsFCID = inputLineFeatures.FeatureClassID;

            // Define the fields for the RoadSplits table

            var ocd = new ObjectClassDescriptionClass() as IObjectClassDescription;
            var fieldsEdit = ocd.RequiredFields as IFieldsEdit;
            IFieldEdit field;

            // Add the anchor edge fields to the table

            field = new FieldClass();
            field.Name_2 = "EdgeFCID";
            field.Type_2 = esriFieldType.esriFieldTypeInteger;
            fieldsEdit.AddField(field);

            field = new FieldClass();
            field.Name_2 = "EdgeFID";
            field.Type_2 = esriFieldType.esriFieldTypeInteger;
            fieldsEdit.AddField(field);

            field = new FieldClass();
            field.Name_2 = "EdgeFrmPos";
            field.Type_2 = esriFieldType.esriFieldTypeDouble;
            fieldsEdit.AddField(field);

            field = new FieldClass();
            field.Name_2 = "EdgeToPos";
            field.Type_2 = esriFieldType.esriFieldTypeDouble;
            fieldsEdit.AddField(field);

            // Add the branch edge fields to the table

            for (int i = 0; i < 3; i++)
            {
                field = new FieldClass();
                field.Name_2 = "Branch" + i + "FCID";
                field.Type_2 = esriFieldType.esriFieldTypeInteger;
                fieldsEdit.AddField(field);

                field = new FieldClass();
                field.Name_2 = "Branch" + i + "FID";
                field.Type_2 = esriFieldType.esriFieldTypeInteger;
                fieldsEdit.AddField(field);

                field = new FieldClass();
                field.Name_2 = "Branch" + i + "FrmPos";
                field.Type_2 = esriFieldType.esriFieldTypeDouble;
                fieldsEdit.AddField(field);

                field = new FieldClass();
                field.Name_2 = "Branch" + i + "ToPos";
                field.Type_2 = esriFieldType.esriFieldTypeDouble;
                fieldsEdit.AddField(field);
            }

            // Check the fields and create the RoadSplits table

            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 roadSplitsTable = fws.CreateTable(RoadSplitsTableName, validatedFields, ocd.InstanceCLSID, ocd.ClassExtensionCLSID, "") as ITable;

            // Find all the fields
            int EdgeFCIDFI = roadSplitsTable.FindField("EdgeFCID");
            int EdgeFIDFI = roadSplitsTable.FindField("EdgeFID");
            int EdgeFrmPosFI = roadSplitsTable.FindField("EdgeFrmPos");
            int EdgeToPosFI = roadSplitsTable.FindField("EdgeToPos");
            int Branch0FCIDFI = roadSplitsTable.FindField("Branch0FCID");
            int Branch0FIDFI = roadSplitsTable.FindField("Branch0FID");
            int Branch0FrmPosFI = roadSplitsTable.FindField("Branch0FrmPos");
            int Branch0ToPosFI = roadSplitsTable.FindField("Branch0ToPos");
            int Branch1FCIDFI = roadSplitsTable.FindField("Branch1FCID");
            int Branch1FIDFI = roadSplitsTable.FindField("Branch1FID");
            int Branch1FrmPosFI = roadSplitsTable.FindField("Branch1FrmPos");
            int Branch1ToPosFI = roadSplitsTable.FindField("Branch1ToPos");
            int Branch2FCIDFI = roadSplitsTable.FindField("Branch2FCID");
            int Branch2FIDFI = roadSplitsTable.FindField("Branch2FID");
            int Branch2FrmPosFI = roadSplitsTable.FindField("Branch2FrmPos");
            int Branch2ToPosFI = roadSplitsTable.FindField("Branch2ToPos");

            // Fetch all line features referenced by the input Rdms table.  We do the
            // "join" this hard way to support all data sources in the sample.
            // Also, for large numbers of special explications, this strategy of fetching all
            // related features and holding them in RAM could be a problem.  To fix
            // this, one could process the input records from the Rdms table in batches.

            System.Collections.Hashtable lineFeaturesList = SignpostUtilities.FillFeatureCache(rdmsTable, linkIDFieldOnRdms, manLinkIDField,
                                                                                               inputLineFeatures, "LINK_ID", trackcancel);

            // Create insert cursor and row buffer for output

            ICursor tableInsertCursor = roadSplitsTable.Insert(true);
            IRowBuffer tableBuffer = roadSplitsTable.CreateRowBuffer();
            IRow row = tableBuffer as IRow;

            // Create input cursor for the Rdms table we are importing

            ITableSort tableSort = new TableSortClass();
            tableSort.Fields = "LINK_ID, COND_ID, SEQ_NUMBER";
            tableSort.set_Ascending("LINK_ID", true);
            tableSort.set_Ascending("COND_ID", true);
            tableSort.set_Ascending("SEQ_NUMBER", true);
            tableSort.QueryFilter = null;
            tableSort.Table = rdmsTable;
            tableSort.Sort(null);
            ICursor inputCursor = tableSort.Rows;

            IRow inputTableRow = inputCursor.NextRow();
            if (inputTableRow == null)
                return;     // if Rdms table is empty, there's nothing to do

            // these are initialized to prevent uninitialized variable compiler error
            SignpostUtilities.FeatureData linkFeatureData = new SignpostUtilities.FeatureData(-1, null);
            SignpostUtilities.FeatureData manLinkFeatureData = new SignpostUtilities.FeatureData(-1, null);

            ICurve fromEdgeCurve, toEdgeCurve;
            IPoint fromEdgeStart, fromEdgeEnd, toEdgeStart, toEdgeEnd;
            double fromEdgeFromPos = 0.0;
            double fromEdgeToPos = 1.0;
            double toEdgeFromPos = 0.0;
            double toEdgeToPos = 1.0;

            long currentLinkID = Convert.ToInt64(inputTableRow.get_Value(linkIDFieldOnRdms));
            long manLinkID = Convert.ToInt64(inputTableRow.get_Value(manLinkIDField));
            try
            {
                linkFeatureData = (SignpostUtilities.FeatureData)lineFeaturesList[currentLinkID];
                manLinkFeatureData = (SignpostUtilities.FeatureData)lineFeaturesList[manLinkID];

                // To set from and to position in the output table, we need see where and
                // if the two edge features connect to figure out their digitized direction.

                fromEdgeCurve = linkFeatureData.feature as ICurve;
                toEdgeCurve = manLinkFeatureData.feature as ICurve;

                fromEdgeStart = fromEdgeCurve.FromPoint;
                fromEdgeEnd = fromEdgeCurve.ToPoint;
                toEdgeStart = toEdgeCurve.FromPoint;
                toEdgeEnd = toEdgeCurve.ToPoint;

                // flip the from edge?

                if (TurnGeometryUtilities.EqualPoints(fromEdgeStart, toEdgeStart) || TurnGeometryUtilities.EqualPoints(fromEdgeStart, toEdgeEnd))
                {
                    fromEdgeFromPos = 1.0;
                    fromEdgeToPos = 0.0;
                }

                // flip the to edge?

                if (TurnGeometryUtilities.EqualPoints(toEdgeEnd, fromEdgeStart) || TurnGeometryUtilities.EqualPoints(toEdgeEnd, fromEdgeEnd))
                {
                    toEdgeFromPos = 1.0;
                    toEdgeToPos = 0.0;
                }

                // set the field values in the buffer

                tableBuffer.set_Value(EdgeFCIDFI, streetsFCID);
                tableBuffer.set_Value(EdgeFIDFI, linkFeatureData.OID);
                tableBuffer.set_Value(EdgeFrmPosFI, fromEdgeFromPos);
                tableBuffer.set_Value(EdgeToPosFI, fromEdgeToPos);
                tableBuffer.set_Value(Branch0FCIDFI, streetsFCID);
                tableBuffer.set_Value(Branch0FIDFI, manLinkFeatureData.OID);
                tableBuffer.set_Value(Branch0FrmPosFI, toEdgeFromPos);
                tableBuffer.set_Value(Branch0ToPosFI, toEdgeToPos);
                tableBuffer.set_Value(Branch1FCIDFI, null);
                tableBuffer.set_Value(Branch1FIDFI, null);
                tableBuffer.set_Value(Branch1FrmPosFI, null);
                tableBuffer.set_Value(Branch1ToPosFI, null);
                tableBuffer.set_Value(Branch2FCIDFI, null);
                tableBuffer.set_Value(Branch2FIDFI, null);
                tableBuffer.set_Value(Branch2FrmPosFI, null);
                tableBuffer.set_Value(Branch2ToPosFI, null);
            }
            catch
            {
                messages.AddWarning("Line feature not found for explication with from ID: " +
                    Convert.ToString(currentLinkID, System.Globalization.CultureInfo.InvariantCulture) +
                    ", To ID: " + Convert.ToString(manLinkID, System.Globalization.CultureInfo.InvariantCulture));
            }

            long previousLinkID = currentLinkID;
            int nextBranch = 1;

            while ((inputTableRow = inputCursor.NextRow()) != null)
            {
                currentLinkID = Convert.ToInt64(inputTableRow.get_Value(linkIDFieldOnRdms));
                manLinkID = Convert.ToInt64(inputTableRow.get_Value(manLinkIDField));
                try
                {
                    linkFeatureData = (SignpostUtilities.FeatureData)lineFeaturesList[currentLinkID];
                    manLinkFeatureData = (SignpostUtilities.FeatureData)lineFeaturesList[manLinkID];
                }
                catch
                {
                    messages.AddWarning("Line feature not found for explication with from ID: " +
                        Convert.ToString(currentLinkID, System.Globalization.CultureInfo.InvariantCulture) +
                        ", To ID: " + Convert.ToString(manLinkID, System.Globalization.CultureInfo.InvariantCulture));
                    continue;
                }

                // To set from and to position in the output table, we need see where and
                // if the two edge features connect to figure out their digitized direction.

                fromEdgeCurve = linkFeatureData.feature as ICurve;
                toEdgeCurve = manLinkFeatureData.feature as ICurve;

                fromEdgeStart = fromEdgeCurve.FromPoint;
                fromEdgeEnd = fromEdgeCurve.ToPoint;
                toEdgeStart = toEdgeCurve.FromPoint;
                toEdgeEnd = toEdgeCurve.ToPoint;

                fromEdgeFromPos = 0.0;
                fromEdgeToPos = 1.0;
                toEdgeFromPos = 0.0;
                toEdgeToPos = 1.0;

                // flip the from edge?

                if (TurnGeometryUtilities.EqualPoints(fromEdgeStart, toEdgeStart) || TurnGeometryUtilities.EqualPoints(fromEdgeStart, toEdgeEnd))
                {
                    fromEdgeFromPos = 1.0;
                    fromEdgeToPos = 0.0;
                }

                // flip the to edge?

                if (TurnGeometryUtilities.EqualPoints(toEdgeEnd, fromEdgeStart) || TurnGeometryUtilities.EqualPoints(toEdgeEnd, fromEdgeEnd))
                {
                    toEdgeFromPos = 1.0;
                    toEdgeToPos = 0.0;
                }

                // set the field values in the buffer

                if (previousLinkID == currentLinkID)
                {
                    switch (nextBranch)
                    {
                        case 1:
                            tableBuffer.set_Value(Branch1FCIDFI, streetsFCID);
                            tableBuffer.set_Value(Branch1FIDFI, manLinkFeatureData.OID);
                            tableBuffer.set_Value(Branch1FrmPosFI, toEdgeFromPos);
                            tableBuffer.set_Value(Branch1ToPosFI, toEdgeToPos);
                            nextBranch = 2;
                            break;
                        case 2:
                            tableBuffer.set_Value(Branch2FCIDFI, streetsFCID);
                            tableBuffer.set_Value(Branch2FIDFI, manLinkFeatureData.OID);
                            tableBuffer.set_Value(Branch2FrmPosFI, toEdgeFromPos);
                            tableBuffer.set_Value(Branch2ToPosFI, toEdgeToPos);
                            nextBranch = 3;
                            break;
                        case 3:
                            messages.AddWarning("There are more than three road splits for From ID: " +
                                Convert.ToString(currentLinkID, System.Globalization.CultureInfo.InvariantCulture));
                            nextBranch = 4;
                            break;
                        case 4:
                            // do nothing here, as there's no need to repeat the warning message.
                            break;
                    }
                }
                else
                {
                    // write out the previous buffered row...
                    tableInsertCursor.InsertRow(tableBuffer);

                    // ...and then set field values in the fresh buffer
                    tableBuffer.set_Value(EdgeFCIDFI, streetsFCID);
                    tableBuffer.set_Value(EdgeFIDFI, linkFeatureData.OID);
                    tableBuffer.set_Value(EdgeFrmPosFI, fromEdgeFromPos);
                    tableBuffer.set_Value(EdgeToPosFI, fromEdgeToPos);
                    tableBuffer.set_Value(Branch0FCIDFI, streetsFCID);
                    tableBuffer.set_Value(Branch0FIDFI, manLinkFeatureData.OID);
                    tableBuffer.set_Value(Branch0FrmPosFI, toEdgeFromPos);
                    tableBuffer.set_Value(Branch0ToPosFI, toEdgeToPos);
                    tableBuffer.set_Value(Branch1FCIDFI, null);
                    tableBuffer.set_Value(Branch1FIDFI, null);
                    tableBuffer.set_Value(Branch1FrmPosFI, null);
                    tableBuffer.set_Value(Branch1ToPosFI, null);
                    tableBuffer.set_Value(Branch2FCIDFI, null);
                    tableBuffer.set_Value(Branch2FIDFI, null);
                    tableBuffer.set_Value(Branch2FrmPosFI, null);
                    tableBuffer.set_Value(Branch2ToPosFI, null);
                    nextBranch = 1;
                }
                previousLinkID = currentLinkID;
            }

            // Write out the final row and flush
            tableInsertCursor.InsertRow(tableBuffer);
            tableInsertCursor.Flush();
        }
示例#29
0
        /// <summary>
        /// 拷贝源图层到空间数据集下的目标图层
        /// </summary>
        /// <param name="sourceWorkspace"></param>
        /// <param name="targetWorkspace"></param>
        /// <param name="nameOfSourceFeatureClass"></param>
        /// <param name="nameOfTargetFeatureClass"></param>
        public static void ConvertFeatureClass(IWorkspace sourceWorkspace, IWorkspace targetWorkspace,
                                               string nameOfSourceFeatureClass, string nameOfTargetFeatureClass)
        {
            try
            {
                //create source workspace name
                IDataset       sourceWorkspaceDataset = (IDataset)sourceWorkspace;
                IWorkspaceName sourceWorkspaceName    = (IWorkspaceName)sourceWorkspaceDataset.FullName;

                //create source dataset name
                IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();

                IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName;
                sourceDatasetName.WorkspaceName = sourceWorkspaceName;
                sourceDatasetName.Name          = nameOfSourceFeatureClass;
                //create target workspace name
                IDataset       targetWorkspaceDataset = (IDataset)targetWorkspace;
                IWorkspaceName targetWorkspaceName    = (IWorkspaceName)targetWorkspaceDataset.FullName;
                //create target dataset name
                IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
                IDatasetName      targetDatasetName      = (IDatasetName)targetFeatureClassName;
                targetDatasetName.WorkspaceName = targetWorkspaceName;
                targetDatasetName.Name          = nameOfTargetFeatureClass;
                //Open input Featureclass to get field definitions.
                IName         sourceName         = (IName)sourceFeatureClassName;
                IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();
                //Validate the field names because you are converting between different workspace types.
                IFieldChecker   fieldChecker = new FieldCheckerClass();
                IFields         targetFeatureClassFields;
                IFields         sourceFeatureClassFields = sourceFeatureClass.Fields;
                IEnumFieldError enumFieldError;
                // Most importantly set the input and validate workspaces!
                fieldChecker.InputWorkspace    = sourceWorkspace;
                fieldChecker.ValidateWorkspace = targetWorkspace;
                fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);
                // Loop through the output fields to find the geomerty field
                IField geometryField;
                for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
                {
                    geometryField = targetFeatureClassFields.get_Field(i);
                    if (geometryField.Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        // Get the geometry field's geometry defenition
                        IGeometryDef geometryDef = geometryField.GeometryDef;

                        //Give the geometry definition a spatial index grid count and grid size
                        IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef;

                        //targetFCGeoDefEdit.GridCount_2 = 1;
                        //targetFCGeoDefEdit.set_GridSize(0, 1000);
                        //Allow ArcGIS to determine a valid grid size for the data loaded
                        targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;
                        // we want to convert all of the features
                        IQueryFilter queryFilter = new QueryFilterClass();
                        queryFilter.WhereClause = "";

                        IEnumDataset    pEnumDataset  = targetWorkspace.get_Datasets(esriDatasetType.esriDTFeatureDataset);
                        IFeatureDataset ipDataset     = (IFeatureDataset)pEnumDataset.Next();
                        IDatasetName    pTargetDsName = (IDatasetName)ipDataset.FullName;
                        // Load the feature class
                        IFeatureDataConverter fctofc = new FeatureDataConverterClass();

                        IEnumInvalidObject enumErrors =
                            fctofc.ConvertFeatureClass(sourceFeatureClassName, queryFilter,
                                                       pTargetDsName as IFeatureDatasetName, targetFeatureClassName,
                                                       geometryDef, targetFeatureClassFields, "", 1000, 0);
                        IInvalidObjectInfo obj = enumErrors.Next();
                        break;
                    }
                }
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                return;
            }
        }
        /// <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;
        }
示例#31
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            ITable table = null;

            switch (this.radioGroup1.SelectedIndex)
            {
            case 0:
                if (this.txtWorkspaceName.Tag != null)
                {
                    IGxDataset      dataset;
                    IFields         fields;
                    IFieldChecker   checker;
                    IEnumFieldError error;
                    IFields         fields2;
                    if (this.txtDatasetName.Text.Trim() == "")
                    {
                        MessageBox.Show("请选择新建数据集的名称!");
                        return;
                    }
                    if (this.SourceDatalistBox.Items.Count == 0)
                    {
                        MessageBox.Show("请选择要合并的数据集!");
                        return;
                    }
                    if (this.rdoDatasetType.SelectedIndex == 0)
                    {
                        if (this.method_0(this.iworkspace_0, esriDatasetType.esriDTFeatureClass,
                                          this.txtDatasetName.Text.Trim()))
                        {
                            MessageBox.Show("指定的要素类名已存在,请输入其它名字!");
                            return;
                        }
                        dataset = this.SourceDatalistBox.Items[0] as IGxDataset;
                        if (dataset.Type != esriDatasetType.esriDTFeatureClass)
                        {
                            MessageBox.Show("要导入的数据集数组中存在和目标数据集不一致数据集,无法完成导入!");
                            return;
                        }
                        if (!this.method_1(dataset.Dataset))
                        {
                            MessageBox.Show("要导入的数据集数组中存在和目标数据集不一致数据集,无法完成导入!");
                            return;
                        }
                        fields  = (dataset.Dataset as ITable).Fields;
                        checker = new FieldCheckerClass
                        {
                            ValidateWorkspace = this.iworkspace_0
                        };
                        checker.Validate(fields, out error, out fields2);
                        table =
                            (this.iworkspace_0 as IFeatureWorkspace).CreateFeatureClass(
                                this.txtDatasetName.Text.Trim(), fields2, null, null, esriFeatureType.esriFTSimple,
                                "Shape", "") as ITable;
                    }
                    else
                    {
                        if (this.method_0(this.iworkspace_0, esriDatasetType.esriDTTable,
                                          this.txtDatasetName.Text.Trim()))
                        {
                            MessageBox.Show("指定的表名已存在,请输入其它名字!");
                            return;
                        }
                        dataset = this.SourceDatalistBox.Items[0] as IGxDataset;
                        if (dataset.Type != esriDatasetType.esriDTTable)
                        {
                            MessageBox.Show("要导入的数据集数组中存在和目标数据集不一致数据集,无法完成导入!");
                            return;
                        }
                        if (this.method_1(dataset.Dataset))
                        {
                            MessageBox.Show("要导入的数据集数组中存在和目标数据集不一致数据集,无法完成导入!");
                            return;
                        }
                        fields  = (dataset.Dataset as ITable).Fields;
                        checker = new FieldCheckerClass
                        {
                            ValidateWorkspace = this.iworkspace_0
                        };
                        checker.Validate(fields, out error, out fields2);
                        table = (this.iworkspace_0 as IFeatureWorkspace).CreateTable(
                            this.txtDatasetName.Text.Trim(), fields2, null, null, "");
                    }
                    break;
                }
                MessageBox.Show("请选择新建数据集所在工作空间!");
                return;

            case 1:
                if (this.txtOutDataset.Tag != null)
                {
                    if (this.SourceDatalistBox.Items.Count == 0)
                    {
                        MessageBox.Show("请选择要合并的数据集!");
                        return;
                    }
                    IDataset dataset2 = (this.txtOutDataset.Tag as IGxDataset).Dataset;
                    if (this.method_1(dataset2))
                    {
                        MessageBox.Show("要导入的数据集数组中存在和目标数据集不一致数据集,无法完成导入!");
                        return;
                    }
                    table = dataset2 as ITable;
                    break;
                }
                MessageBox.Show("请选择数据导入的目标数据集!");
                return;
            }
            IList       items       = this.SourceDatalistBox.Items;
            Dataloaders dataloaders = new Dataloaders();

            for (int i = 0; i < items.Count; i++)
            {
                this.lblProcess.Text = "开始导入 " + (items[i] as IGxObject).FullName + " ...";
                ITable table2 = (items[i] as IGxObject).InternalObjectName.Open() as ITable;
                dataloaders.LoadData(table2, null, table, 800);
                Marshal.ReleaseComObject(table2);
                table2 = null;
            }
            MessageBox.Show("数据合并完成!");
            base.DialogResult = DialogResult.OK;
            base.Close();
        }
        public ITable createTable(IWorkspace wks, string tableName, IFields atrflds)
        {
            IWorkspace2 wks2 = (IWorkspace2)wks;
            IFeatureWorkspace ftrWks = (IFeatureWorkspace)wks;
            ITable tbl = null;
            try
            {

                if (wks2.get_NameExists(esriDatasetType.esriDTTable, tableName))
                {
                    return tbl;
                }

                IObjectClassDescription ocDescription = new ObjectClassDescriptionClass();
                IFields fields = ocDescription.RequiredFields;
                IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
                if (atrflds != null)
                {
                    for (int i = 0; i < atrflds.FieldCount; i++)
                    {
                        IField fld = atrflds.get_Field(i);
                        fieldsEdit.AddField(fld);
                    }
                }
                // 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);
                tbl = ftrWks.CreateTable(tableName, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, "");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }
            return tbl;
        }
示例#33
0
        //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;
            }
        }
        /// <summary>
        /// 创建要素图层
        /// 也可以利用现有要素图层创建:IFeatureLayer featurelayer,
        /// </summary>
        /// <params name="map"></params>
        /// <params name="workspace"></params>
        /// <params name="layername"></params>
        /// <params name="aliasname"></params>
        /// <returns></returns>
        public IFeatureLayer CreateFeatureLayer(IMap map, IWorkspace workspace,
            string layername, string aliasname)
        {
            try
            {
                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;
                //IFields fields = featurelayer.FeatureClass.Fields;

                // 创建要素类的字段集
                IFields fields = new FieldsClass();
                IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

                // 添加要素类必须字段:object ID 字段
                IField oidField = new FieldClass();
                IFieldEdit oidFieldEdit = (IFieldEdit)oidField;
                oidFieldEdit.Name_2 = "OBJECTID";
                oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
                fieldsEdit.AddField(oidField);

                // 创建几何定义(和空间参考)
                IGeometryDef geometryDef = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
                //ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                //ISpatialReference spatialReference =
                //spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_20N);
                //ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;
                //spatialReferenceResolution.ConstructFromHorizon();
                //ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;
                //spatialReferenceTolerance.SetDefaultXYTolerance();
                geometryDefEdit.SpatialReference_2 = map.SpatialReference;

                //添加几何字段
                IField geometryField = new FieldClass();
                IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField;
                geometryFieldEdit.Name_2 = "Shape";
                geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
                geometryFieldEdit.GeometryDef_2 = geometryDef;
                fieldsEdit.AddField(geometryField);

                //新建字段
                IField pField = new FieldClass();
                IFieldEdit pFieldEdit = pField as IFieldEdit;
                pFieldEdit.Length_2 = 50;
                pFieldEdit.Name_2 = "ID";
                pFieldEdit.AliasName_2 = "ID";
                pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                fieldsEdit.AddField(pField);

                //检查字段的有效性
                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(layername, validatedFields, null, null,
                    esriFeatureType.esriFTSimple, "Shape", "");

                //用创建的要素类生成要素图层
                IFeatureLayer newFeaLayer = new FeatureLayerClass();
                newFeaLayer.FeatureClass = featureClass;
                newFeaLayer.Name = aliasname;

                //添加新建图层到相应图层组中
                IGroupLayer groupLayer = new GroupLayerClass();
                string groupLayerName = aliasname.Split("-".ToCharArray())[1].Trim();
                groupLayer = GetGroupLayerByName(groupLayerName);
                groupLayer.Add(newFeaLayer as ILayer);
                DataEditCommon.g_axTocControl.Update();
                DataEditCommon.g_pAxMapControl.Refresh();

                return newFeaLayer;
            }
            catch (Exception ex)
            {
                Log.Debug(ex.ToString());
                return null;
            }
        }
示例#35
0
        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>
        /// shape图层入库
        /// </summary>
        /// <params name="sourceworkspace"></params>
        /// <params name="targetworkspace"></params>
        /// <params name="nameOfsourceFeatureClass"></params>
        /// <params name="nameOftargetFeatureClass"></params>
        /// <returns></returns>
        public IFeatureClass ShapeFileIntoGDB(IWorkspace sourceworkspace,IWorkspace targetworkspace,
            string nameOfsourceFeatureClass, string nameOftargetFeatureClass)
        {
            try
            {
                //创建源工作空间
                IDataset sourceWorkspaceDataset = (IDataset)sourceworkspace;
                IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDataset.FullName;

                //创建源数据集
                IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
                IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName;
                sourceDatasetName.WorkspaceName = sourceWorkspaceName;
                sourceDatasetName.Name = nameOfsourceFeatureClass;

                //创建目标工作空间
                IDataset targetWorkspaceDataset = (IDataset)targetworkspace;
                IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDataset.FullName;

                //创建目标数据集
                IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
                IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName;
                targetDatasetName.WorkspaceName = targetWorkspaceName;
                targetDatasetName.Name = nameOftargetFeatureClass;

                //源数据集的字段集
                IName sourceName = (IName)sourceFeatureClassName;
                IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();

                //验证字段
                IFieldChecker fieldChecker = new FieldCheckerClass();
                IFields targetFeatureClassFields;
                IFields sourceFeatureClassFields = sourceFeatureClass.Fields;
                IEnumFieldError enumFieldError;

                //设置验证的对象
                fieldChecker.InputWorkspace = sourceworkspace;
                fieldChecker.ValidateWorkspace = targetworkspace;
                fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);

                //找到空间对象字段
                IField geometryField;
                for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
                {
                    if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        geometryField = targetFeatureClassFields.get_Field(i);

                        //得到空间字段的定义
                        IGeometryDef geometryDef = geometryField.GeometryDef;

                        //得到空间字段的索引
                        IGeometryDefEdit targetFCGeometryDefEdit = (IGeometryDefEdit)geometryDef;
                        targetFCGeometryDefEdit.GridCount_2 = 1;
                        targetFCGeometryDefEdit.set_GridSize(0, 0);
                        //targetFCGeometryDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;

                        ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                        ISpatialReference spatialReference = DataEditCommon.g_pMap.SpatialReference;
                        //spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_20N);
                        ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;
                        spatialReferenceResolution.ConstructFromHorizon();
                        spatialReferenceResolution.SetDefaultXYResolution();
                        spatialReferenceResolution.SetDefaultZResolution();
                        ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;
                        spatialReferenceTolerance.SetMinimumXYTolerance();
                        spatialReferenceTolerance.SetMinimumZTolerance();

                        double XMin, XMax, YMin, YMax, ZMin, ZMax, MinXYTolerance, MinZTolerance;
                        XMin = 4054.3603997438;
                        XMax = 78088.6926632544;
                        YMin = 14424.8510028409;
                        YMax = 59609.4812606697;
                        ZMin = 30330.1483519995;
                        ZMax = 38389.3283520005;
                        //spatialReference.SetDomain(XMin, XMax, YMin, YMax);
                        //spatialReference.SetZDomain(ZMin, ZMax);

                        MinXYTolerance = 0.000000000008219;
                        MinZTolerance = 0.000000000007629;
                        //spatialReferenceTolerance.SetMinimumZTolerance( MinXYTolerance);

                        //spatialReference.GetDomain(out XMin, out XMax, out YMin, out YMax);
                        //spatialReference.GetZDomain(out ZMin, out ZMax);

                        targetFCGeometryDefEdit.SpatialReference_2 = spatialReference;

                        //开始导入
                        IQueryFilter queryFilter = new QueryFilterClass();
                        queryFilter.WhereClause = "";

                        //导入所有的输入对象
                        IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass();
                        IEnumInvalidObject enumInvalidObject = featureDataConverter.ConvertFeatureClass(sourceFeatureClassName,
                            queryFilter, null, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0);
                        break;
                    }
                }

                //导入后数据集的字段集
                IName targetName = (IName)targetFeatureClassName;
                IFeatureClass targetFeatureClass = (IFeatureClass)targetName.Open();

                return targetFeatureClass;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
示例#37
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            if ((m_MatchedFCName != "") && (m_WorkspacePath != ""))
            {
                //判断选择字段是否对应
                for (int i = 0; i < dataGridViewX1.RowCount; i++)
                {
                    DataGridViewCheckBoxCell dgvCheckBoxCell1 = dataGridViewX1[0, i] as DataGridViewCheckBoxCell;
                    if (Convert.ToBoolean(dgvCheckBoxCell1.Value) == true)//判断是否进行属性匹配,若进行,必须选取对应字段
                    {
                        if (this.dataGridViewX1[2, i].Value == null)
                        {
                            MessageBoxEx.Show("所选字段没有完全对应,请重新检查!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                }

                IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactory();
                IWorkspace2       workspace         = pWorkspaceFactory.OpenFromFile(m_WorkspacePath, 0) as IWorkspace2;
                IFeatureWorkspace featureWorkspace  = workspace as IFeatureWorkspace;
                ITable            table             = null;
                IFields           fields            = null;

                if (m_TUFeatCls.ShapeType == esriGeometryType.esriGeometryPolygon)
                {
                    if (workspace.get_NameExists(esriDatasetType.esriDTTable, "MatchedPolygonFCSetting"))
                    {
                        table = featureWorkspace.OpenTable("MatchedPolygonFCSetting");
                    }
                    else
                    {
                        fields = CreateMatchedPolygonFCSettingFields(workspace);
                        UID uid = new UIDClass();
                        uid.Value = "esriGeoDatabase.Object";
                        IFieldChecker   fieldChecker    = new FieldCheckerClass();
                        IEnumFieldError enumFieldError  = null;
                        IFields         validatedFields = null;
                        fieldChecker.ValidateWorkspace = (IWorkspace)workspace;
                        fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

                        table = featureWorkspace.CreateTable("MatchedPolygonFCSetting", validatedFields, uid, null, "");
                    }
                }

                IWorkspaceEdit pWorkspaceEdit = featureWorkspace as IWorkspaceEdit;
                pWorkspaceEdit.StartEditing(true);
                pWorkspaceEdit.StartEditOperation();

                //Collection<string> pCol = new Collection<string>();
                Dictionary <string, int> pDic = new Dictionary <string, int>();

                string tempFieldsName = "";
                DataGridViewCheckBoxCell dgvCheckBoxCell = new DataGridViewCheckBoxCell();

                //查看是否MatchedFCName是否存在,当前为工作层
                int     index   = table.FindField("MatchedFCName");
                ICursor pCursor = table.Search(null, false);
                IRow    pRow    = pCursor.NextRow();
                while (pRow != null)
                {
                    if (pRow.get_Value(index).ToString() != "")
                    {
                        pDic.Add(pRow.get_Value(index).ToString(), pRow.OID);
                    }
                    pRow = pCursor.NextRow();
                }

                if (this.tabControl1.Tabs[0].Visible)
                {
                    if (!pDic.ContainsKey(m_MatchedFCName))
                    {
                        IRow tempRow = table.CreateRow();
                        tempRow.set_Value(index, m_MatchedFCName);
                        tempRow.set_Value(tempRow.Fields.FindField("FCSettingID"), table.RowCount(null) - 1);

                        if (this.radioButtonCenter.Checked == true)
                        {
                            tempRow.set_Value(tempRow.Fields.FindField("Center"), 1);//权重为一
                            tempRow.set_Value(tempRow.Fields.FindField("CenterNum"), this.txtCenterNum.Text);
                            //tempRow.set_Value(tempRow.Fields.FindField("CenterWT"), this.txtCenterWT.Text);
                        }
                        else
                        {
                            tempRow.set_Value(tempRow.Fields.FindField("Center"), 0);
                        }

                        if (this.radioButtonArea.Checked == true)
                        {
                            tempRow.set_Value(tempRow.Fields.FindField("Area"), 1);
                            tempRow.set_Value(tempRow.Fields.FindField("AreaNum"), this.txtAreaNum.Text);
                            //tempRow.set_Value(tempRow.Fields.FindField("AreaWT"), this.txtAreaWT.Text);
                        }
                        else
                        {
                            tempRow.set_Value(tempRow.Fields.FindField("Area"), 0);
                        }

                        if (this.radioButtonShape.Checked == true)
                        {
                            tempRow.set_Value(tempRow.Fields.FindField("SP"), 1);
                            tempRow.set_Value(tempRow.Fields.FindField("SPNum"), this.txtSPNum.Text);
                            //tempRow.set_Value(tempRow.Fields.FindField("SPWT"), this.txtSPWT.Text);
                        }
                        else
                        {
                            tempRow.set_Value(tempRow.Fields.FindField("SP"), 0);
                        }
                        //修改属性!!!!!!!!!!!!!!!!!!!!!
                        tempRow.set_Value(tempRow.Fields.FindField("Attribute"), 1);
                        for (int i = 0; i < dataGridViewX1.RowCount; i++)
                        {
                            dgvCheckBoxCell = dataGridViewX1[0, i] as DataGridViewCheckBoxCell;
                            if (Convert.ToBoolean(dgvCheckBoxCell.Value) == true)
                            {
                                if (this.dataGridViewX1[1, i].Value.ToString().ToUpper() == this.dataGridViewX1[2, i].Value.ToString().ToUpper())
                                {
                                    tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + ";";
                                }
                                else
                                {
                                    tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + "(" + dataGridViewX1[2, i].Value.ToString() + ")";
                                }
                            }
                        }

                        if (tempFieldsName == "")
                        {
                            //tRow.set_Value(tRow.Fields.FindField("Attribute"), 0);
                            MessageBoxEx.Show("没有选择属性匹配对应字段!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            //tRow.set_Value(tRow.Fields.FindField("Attribute"), 1);
                            tempRow.set_Value(tempRow.Fields.FindField("MatchedFields"), tempFieldsName.Trim());
                        }

                        IDataset dataset = m_TUFeatCls as IDataset;
                        if (ClsDeclare.g_SourceFeatClsPathDic.ContainsKey(dataset.Name))
                        {
                            tempRow.set_Value(tempRow.Fields.FindField("SourceFCName"), dataset.Name);
                            tempRow.set_Value(tempRow.Fields.FindField("SourcePath"), ClsDeclare.g_SourceFeatClsPathDic[dataset.Name]);
                            tempRow.set_Value(tempRow.Fields.FindField("WorkspacePath"), ClsDeclare.g_WorkspacePath);
                        }
                        tempRow.Store();
                    }
                    else
                    {
                        IRow tRow = table.GetRow(pDic[m_MatchedFCName]);
                        if (this.radioButtonCenter.Checked == true)
                        {
                            tRow.set_Value(tRow.Fields.FindField("Center"), 1);
                            tRow.set_Value(tRow.Fields.FindField("CenterNum"), this.txtCenterNum.Text);
                            //tRow.set_Value(tRow.Fields.FindField("CenterWT"), this.txtCenterWT.Text);
                        }
                        else
                        {
                            tRow.set_Value(tRow.Fields.FindField("Center"), 0);
                            tRow.set_Value(tRow.Fields.FindField("CenterNum"), 0);
                        }

                        if (this.radioButtonArea.Checked == true)
                        {
                            tRow.set_Value(tRow.Fields.FindField("Area"), 1);
                            tRow.set_Value(tRow.Fields.FindField("AreaNum"), this.txtAreaNum.Text);
                            //tRow.set_Value(tRow.Fields.FindField("AreaWT"), this.txtAreaWT.Text);
                        }
                        else
                        {
                            tRow.set_Value(tRow.Fields.FindField("Area"), 0);
                            tRow.set_Value(tRow.Fields.FindField("AreaNum"), 0);
                        }

                        if (this.radioButtonShape.Checked == true)
                        {
                            tRow.set_Value(tRow.Fields.FindField("SP"), 1);
                            tRow.set_Value(tRow.Fields.FindField("SPNum"), this.txtSPNum.Text);
                            //tRow.set_Value(tRow.Fields.FindField("SPWT"), this.txtSPWT.Text);
                        }
                        else
                        {
                            tRow.set_Value(tRow.Fields.FindField("SP"), 0);
                            tRow.set_Value(tRow.Fields.FindField("SPNum"), 0);
                        }
                        //修改属性!!!!!!!!!!!!
                        tRow.set_Value(tRow.Fields.FindField("Attribute"), 1);
                        for (int i = 0; i < dataGridViewX1.RowCount; i++)
                        {
                            dgvCheckBoxCell = dataGridViewX1[0, i] as DataGridViewCheckBoxCell;
                            if (Convert.ToBoolean(dgvCheckBoxCell.Value) == true)
                            {
                                if (this.dataGridViewX1[1, i].Value.ToString().ToUpper() == this.dataGridViewX1[2, i].Value.ToString().ToUpper())
                                {
                                    tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + ";";
                                }
                                else
                                {
                                    tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + "(" + dataGridViewX1[2, i].Value.ToString() + ")";
                                }
                            }
                        }

                        if (tempFieldsName == "")
                        {
                            //tRow.set_Value(tRow.Fields.FindField("Attribute"), 0);
                            MessageBoxEx.Show("没有选择属性匹配对应字段!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            //tRow.set_Value(tRow.Fields.FindField("Attribute"), 1);
                            tRow.set_Value(tRow.Fields.FindField("MatchedFields"), tempFieldsName.Trim());
                        }

                        IDataset dataset = m_TUFeatCls as IDataset;
                        if (ClsDeclare.g_SourceFeatClsPathDic.ContainsKey(dataset.Name))
                        {
                            tRow.set_Value(tRow.Fields.FindField("SourceFCName"), dataset.Name);
                            tRow.set_Value(tRow.Fields.FindField("SourcePath"), ClsDeclare.g_SourceFeatClsPathDic[dataset.Name]);
                            tRow.set_Value(tRow.Fields.FindField("WorkspacePath"), ClsDeclare.g_WorkspacePath);
                        }
                        tRow.Store();
                    }
                }
                else if (this.tabControl1.Tabs[1].Visible)
                {
                    if (!pDic.ContainsKey(m_MatchedFCName))
                    {
                        IRow tempRow = table.CreateRow();
                        tempRow.set_Value(index, m_MatchedFCName);
                        tempRow.set_Value(tempRow.Fields.FindField("FCSettingID"), table.RowCount(null) - 1);
                        tempRow.set_Value(tempRow.Fields.FindField("Top"), 1);

                        if (this.comboBoxExBuffer.Text != "")
                        {
                            tempRow.set_Value(tempRow.Fields.FindField("Buffer"), this.comboBoxExBuffer.Text);
                        }
                        else
                        {
                            MessageBox.Show("请选择缓冲区半径!");
                            return;
                        }
                        //修改属性!!!!!!!!!!!!
                        tempRow.set_Value(tempRow.Fields.FindField("Attribute"), 1);
                        for (int i = 0; i < dataGridViewX1.RowCount; i++)
                        {
                            dgvCheckBoxCell = dataGridViewX1[0, i] as DataGridViewCheckBoxCell;
                            if (Convert.ToBoolean(dgvCheckBoxCell.Value) == true)
                            {
                                if (this.dataGridViewX1[1, i].Value.ToString().ToUpper() == this.dataGridViewX1[2, i].Value.ToString().ToUpper())
                                {
                                    tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + ";";
                                }
                                else
                                {
                                    tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + "(" + dataGridViewX1[2, i].Value.ToString() + ")";
                                }
                            }
                        }

                        if (tempFieldsName == "")
                        {
                            //tRow.set_Value(tRow.Fields.FindField("Attribute"), 0);
                            MessageBoxEx.Show("没有选择属性匹配对应字段!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            //tRow.set_Value(tRow.Fields.FindField("Attribute"), 1);
                            tempRow.set_Value(tempRow.Fields.FindField("MatchedFields"), tempFieldsName.Trim());
                        }
                        IDataset dataset = m_TUFeatCls as IDataset;
                        if (ClsDeclare.g_SourceFeatClsPathDic.ContainsKey(dataset.Name))
                        {
                            tempRow.set_Value(tempRow.Fields.FindField("SourceFCName"), dataset.Name);
                            tempRow.set_Value(tempRow.Fields.FindField("SourcePath"), ClsDeclare.g_SourceFeatClsPathDic[dataset.Name]);
                            tempRow.set_Value(tempRow.Fields.FindField("WorkspacePath"), ClsDeclare.g_WorkspacePath);
                        }
                        tempRow.Store();
                    }
                    else
                    {
                        IRow tRow = table.GetRow(pDic[m_MatchedFCName]);
                        tRow.set_Value(tRow.Fields.FindField("Top"), 1);
                        if (this.comboBoxExBuffer.Text != "")
                        {
                            tRow.set_Value(tRow.Fields.FindField("Buffer"), this.comboBoxExBuffer.Text);
                        }
                        else
                        {
                            MessageBoxEx.Show("请选择缓冲区半径!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        //修改属性!!!!!!!!!!!!
                        tRow.set_Value(tRow.Fields.FindField("Attribute"), 1);
                        for (int i = 0; i < dataGridViewX1.RowCount; i++)
                        {
                            dgvCheckBoxCell = dataGridViewX1[0, i] as DataGridViewCheckBoxCell;
                            if (Convert.ToBoolean(dgvCheckBoxCell.Value) == true)
                            {
                                if (this.dataGridViewX1[1, i].Value.ToString().ToUpper() == this.dataGridViewX1[2, i].Value.ToString().ToUpper())
                                {
                                    tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + ";";
                                }
                                else
                                {
                                    tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + "(" + dataGridViewX1[2, i].Value.ToString() + ")";
                                }
                            }
                        }

                        if (tempFieldsName == "")
                        {
                            //tRow.set_Value(tRow.Fields.FindField("Attribute"), 0);
                            MessageBoxEx.Show("没有选择属性匹配对应字段!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            //tRow.set_Value(tRow.Fields.FindField("Attribute"), 1);
                            tRow.set_Value(tRow.Fields.FindField("MatchedFields"), tempFieldsName.Trim());
                        }

                        IDataset dataset = m_TUFeatCls as IDataset;
                        if (ClsDeclare.g_SourceFeatClsPathDic.ContainsKey(dataset.Name))
                        {
                            tRow.set_Value(tRow.Fields.FindField("SourceFCName"), dataset.Name);
                            tRow.set_Value(tRow.Fields.FindField("SourcePath"), ClsDeclare.g_SourceFeatClsPathDic[dataset.Name]);
                            tRow.set_Value(tRow.Fields.FindField("WorkspacePath"), ClsDeclare.g_WorkspacePath);
                        }
                        tRow.Store();
                    }
                }
                pWorkspaceEdit.StopEditOperation();
                pWorkspaceEdit.StopEditing(true);
            }
            m_dgvCell.Value = "已设置";
            this.Close();
            return;
        }
示例#38
0
        /// <summary>
        /// 拷贝源表到目标空间
        /// </summary>
        /// <param name="sourceWorkspace"></param>
        /// <param name="targetWorkspace"></param>
        /// <param name="SourceDataset"></param>
        /// <param name="nameOfTargetDataset"></param>
        public static void ConvertTable(IWorkspace sourceWorkspace, IWorkspace targetWorkspace, IDataset SourceDataset,
                                        string nameOfTargetDataset)
        {
            try
            {
                //create source workspace name
                ITable pSourceTab = (ITable)SourceDataset;

                IDataset sourceWorkspaceDataset = (IDataset)sourceWorkspace;
                IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDataset.FullName;

                IDatasetName sourceDatasetName = (IDatasetName)SourceDataset.FullName;

                //create target workspace name
                IDataset targetWorkspaceDataset = (IDataset)targetWorkspace;
                IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDataset.FullName;
                //create target dataset name
                ITableName targetTableName = new FeatureClassNameClass();
                IDatasetName targetDatasetName = (IDatasetName)targetTableName;
                targetDatasetName.WorkspaceName = targetWorkspaceName;
                targetDatasetName.Name = nameOfTargetDataset;
                ////Open input Featureclass to get field definitions.
                //ESRI.ArcGIS.esriSystem.IName sourceName = (ESRI.ArcGIS.esriSystem.IName)sourceDatasetName;
                //ITable sourceTable = (ITable)sourceName.Open();

                // we want to convert all of the features
                IQueryFilter queryFilter = new QueryFilterClass();
                queryFilter.WhereClause = "";
                //Validate the field names because you are converting between different workspace types.
                IFieldChecker fieldChecker = new FieldCheckerClass();
                IFields targetFields;
                IFields sourceFields = pSourceTab.Fields;
                IEnumFieldError enumFieldError;
                // Most importantly set the input and validate workspaces!
                fieldChecker.InputWorkspace = sourceWorkspace;
                fieldChecker.ValidateWorkspace = targetWorkspace;
                fieldChecker.Validate(sourceFields, out enumFieldError, out targetFields);
                if (enumFieldError == null)
                {
                    IFeatureDataConverter fctofc = new FeatureDataConverterClass();

                    IEnumInvalidObject enumErrors =
                        fctofc.ConvertTable(sourceDatasetName, queryFilter, targetDatasetName, pSourceTab.Fields, "",
                                            1000, 0);
                }
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                return;
            }
        }
示例#39
0
        /// <summary>
        /// shape图层入库
        /// </summary>
        /// <param name="sourceworkspace"></param>
        /// <param name="targetworkspace"></param>
        /// <param name="nameOfsourceFeatureClass"></param>
        /// <param name="nameOftargetFeatureClass"></param>
        /// <returns></returns>
        public IFeatureClass ShapeFileIntoGDB(IWorkspace sourceworkspace, IWorkspace targetworkspace,
                                              string nameOfsourceFeatureClass, string nameOftargetFeatureClass)
        {
            try
            {
                //创建源工作空间
                IDataset       sourceWorkspaceDataset = (IDataset)sourceworkspace;
                IWorkspaceName sourceWorkspaceName    = (IWorkspaceName)sourceWorkspaceDataset.FullName;

                //创建源数据集
                IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
                IDatasetName      sourceDatasetName      = (IDatasetName)sourceFeatureClassName;
                sourceDatasetName.WorkspaceName = sourceWorkspaceName;
                sourceDatasetName.Name          = nameOfsourceFeatureClass;

                //创建目标工作空间
                IDataset       targetWorkspaceDataset = (IDataset)targetworkspace;
                IWorkspaceName targetWorkspaceName    = (IWorkspaceName)targetWorkspaceDataset.FullName;

                //创建目标数据集
                IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
                IDatasetName      targetDatasetName      = (IDatasetName)targetFeatureClassName;
                targetDatasetName.WorkspaceName = targetWorkspaceName;
                targetDatasetName.Name          = nameOftargetFeatureClass;

                //源数据集的字段集
                IName         sourceName         = (IName)sourceFeatureClassName;
                IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();

                //验证字段
                IFieldChecker   fieldChecker = new FieldCheckerClass();
                IFields         targetFeatureClassFields;
                IFields         sourceFeatureClassFields = sourceFeatureClass.Fields;
                IEnumFieldError enumFieldError;

                //设置验证的对象
                fieldChecker.InputWorkspace    = sourceworkspace;
                fieldChecker.ValidateWorkspace = targetworkspace;
                fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);

                //找到空间对象字段
                IField geometryField;
                for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
                {
                    if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        geometryField = targetFeatureClassFields.get_Field(i);

                        //得到空间字段的定义
                        IGeometryDef geometryDef = geometryField.GeometryDef;

                        //得到空间字段的索引
                        IGeometryDefEdit targetFCGeometryDefEdit = (IGeometryDefEdit)geometryDef;
                        targetFCGeometryDefEdit.GridCount_2 = 1;
                        targetFCGeometryDefEdit.set_GridSize(0, 0);
                        //targetFCGeometryDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;

                        ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                        ISpatialReference        spatialReference        = DataEditCommon.g_pMap.SpatialReference;
                        //spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_20N);
                        ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;
                        spatialReferenceResolution.ConstructFromHorizon();
                        spatialReferenceResolution.SetDefaultXYResolution();
                        spatialReferenceResolution.SetDefaultZResolution();
                        ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;
                        spatialReferenceTolerance.SetMinimumXYTolerance();
                        spatialReferenceTolerance.SetMinimumZTolerance();

                        double XMin, XMax, YMin, YMax, ZMin, ZMax, MinXYTolerance, MinZTolerance;
                        XMin = 4054.3603997438;
                        XMax = 78088.6926632544;
                        YMin = 14424.8510028409;
                        YMax = 59609.4812606697;
                        ZMin = 30330.1483519995;
                        ZMax = 38389.3283520005;
                        //spatialReference.SetDomain(XMin, XMax, YMin, YMax);
                        //spatialReference.SetZDomain(ZMin, ZMax);

                        MinXYTolerance = 0.000000000008219;
                        MinZTolerance  = 0.000000000007629;
                        //spatialReferenceTolerance.SetMinimumZTolerance( MinXYTolerance);

                        //spatialReference.GetDomain(out XMin, out XMax, out YMin, out YMax);
                        //spatialReference.GetZDomain(out ZMin, out ZMax);


                        targetFCGeometryDefEdit.SpatialReference_2 = spatialReference;


                        //开始导入
                        IQueryFilter queryFilter = new QueryFilterClass();
                        queryFilter.WhereClause = "";

                        //导入所有的输入对象
                        IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass();
                        IEnumInvalidObject    enumInvalidObject    = featureDataConverter.ConvertFeatureClass(sourceFeatureClassName,
                                                                                                              queryFilter, null, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0);
                        break;
                    }
                }

                //导入后数据集的字段集
                IName         targetName         = (IName)targetFeatureClassName;
                IFeatureClass targetFeatureClass = (IFeatureClass)targetName.Open();

                return(targetFeatureClass);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
示例#40
0
 /// <summary>return a validated set of fields</summary>
 /// <param name="workspace">the input workspace</param>
 /// <param name="fields">the input fields</param>
 /// <returns></returns>
 public static IFields validateFields( IWorkspace workspace, IFields fields)
 {
     // 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 validatedFields;
 }
示例#41
0
        /// <summary>
        /// convert featureclass in shapefile
        /// </summary>
        /// <param name="sourceWorkspace">oggetto workspace</param>
        /// <param name="outputName">nome feature class e nome shapefile</param>
        /// <param name="targetWorkspacePath">cartella shapefile</param>
        /// <param name="errorField">lista degli eventuali errori nella creazione dei campi</param>
        /// <param name="invalidObject">lista degli eventuale errori di creazione record</param>
        private void ConvertFeatureClassToShapefile(IWorkspace sourceWorkspace, string outputName, string targetWorkspacePath, ref List <string> errorField, ref List <string> invalidObject)
        {
            IWorkspace targetWorkspace = null;

            try
            {
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesFile.ShapefileWorkspaceFactory");
                IWorkspaceFactory targetWorkspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                targetWorkspace = targetWorkspaceFactory.OpenFromFile(targetWorkspacePath, 0);

                // Cast the workspaces to the IDataset interface and get name objects.
                IDataset       sourceWorkspaceDataset     = (IDataset)sourceWorkspace;
                IDataset       targetWorkspaceDataset     = (IDataset)targetWorkspace;
                IName          sourceWorkspaceDatasetName = sourceWorkspaceDataset.FullName;
                IName          targetWorkspaceDatasetName = targetWorkspaceDataset.FullName;
                IWorkspaceName sourceWorkspaceName        = (IWorkspaceName)sourceWorkspaceDatasetName;
                IWorkspaceName targetWorkspaceName        = (IWorkspaceName)targetWorkspaceDatasetName;

                // Create a name object for the shapefile and cast it to the IDatasetName interface.
                IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
                IDatasetName      sourceDatasetName      = (IDatasetName)sourceFeatureClassName;
                sourceDatasetName.Name          = outputName;
                sourceDatasetName.WorkspaceName = sourceWorkspaceName;

                // Create a name object for the FGDB feature class and cast it to the IDatasetName interface.
                IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
                IDatasetName      targetDatasetName      = (IDatasetName)targetFeatureClassName;
                targetDatasetName.Name          = outputName;
                targetDatasetName.WorkspaceName = targetWorkspaceName;

                // Open source feature class to get field definitions.
                IName         sourceName         = (IName)sourceFeatureClassName;
                IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();

                // Create the objects and references necessary for field validation.
                IFieldChecker   fieldChecker   = new FieldCheckerClass();
                IFields         sourceFields   = sourceFeatureClass.Fields;
                IFields         targetFields   = null;
                IEnumFieldError enumFieldError = null;

                // Set the required properties for the IFieldChecker interface.
                fieldChecker.InputWorkspace    = sourceWorkspace;
                fieldChecker.ValidateWorkspace = targetWorkspace;

                // Validate the fields and check for errors.
                fieldChecker.Validate(sourceFields, out enumFieldError, out targetFields);
                if (enumFieldError != null)
                {
                    IFieldError fieldError = null;
                    enumFieldError.Reset();
                    while ((fieldError = enumFieldError.Next()) != null)
                    {
                        errorField.Add($"Errore: {Enum.GetName(typeof(esriFieldNameErrorType), fieldError.FieldError)} - Campo: {targetFields.get_Field(fieldError.FieldIndex).Name}");
                    }
                }

                // Find the shape field.
                string shapeFieldName  = sourceFeatureClass.ShapeFieldName;
                int    shapeFieldIndex = sourceFeatureClass.FindField(shapeFieldName);
                IField shapeField      = sourceFields.get_Field(shapeFieldIndex);

                // Get the geometry definition from the shape field and clone it.
                IGeometryDef geometryDef            = shapeField.GeometryDef;
                IClone       geometryDefClone       = (IClone)geometryDef;
                IClone       targetGeometryDefClone = geometryDefClone.Clone();
                IGeometryDef targetGeometryDef      = (IGeometryDef)targetGeometryDefClone;

                // Create the converter and run the conversion.
                IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass();
                IEnumInvalidObject    enumInvalidObject    =
                    featureDataConverter.ConvertFeatureClass(sourceFeatureClassName,
                                                             null, null, targetFeatureClassName, targetGeometryDef, targetFields,
                                                             string.Empty, 1000, 0);

                // Check for errors.
                IInvalidObjectInfo invalidObjectInfo = null;
                enumInvalidObject.Reset();
                while ((invalidObjectInfo = enumInvalidObject.Next()) != null)
                {
                    invalidObject.Add($"{invalidObjectInfo.InvalidObjectID}");
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (targetWorkspace != null)
                {
                    Marshal.FinalReleaseComObject(targetWorkspace);
                }
            }
        }
        /// <summary>
        /// 将一个要素类从一个工作空间转移到另外一个工作空间
        /// 注意目标工作空间不能有改要素类,必须先清除  
        /// </summary>
        /// <params name="sourceWorkspace">源工作空间</params>
        /// <params name="targetWorkspace">目标工作空间</params>
        /// <params name="nameOfSourceFeatureClass">源要素类名</params>
        /// <params name="nameOfTargetFeatureClass">目标要素类名</params>
        public bool IFeatureDataConverter_ConvertFeatureClass(IWorkspace sourceWorkspace, IWorkspace targetWorkspace, string nameOfSourceFeatureClass, string nameOfTargetFeatureClass)
        {
            bool change = false;
            //create source workspace name
            IDataset sourceWorkspaceDataset = (IDataset)sourceWorkspace;
            IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDataset.FullName;
            //create source dataset name
            IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
            IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName;
            sourceDatasetName.WorkspaceName = sourceWorkspaceName;
            sourceDatasetName.Name = nameOfSourceFeatureClass;
            //create target workspace name
            IDataset targetWorkspaceDataset = (IDataset)targetWorkspace;
            IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDataset.FullName;
            //create target dataset name
            IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
            IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName;
            targetDatasetName.WorkspaceName = targetWorkspaceName;
            targetDatasetName.Name = nameOfTargetFeatureClass;
            //Open input Featureclass to get field definitions.
            ESRI.ArcGIS.esriSystem.IName sourceName = (ESRI.ArcGIS.esriSystem.IName)sourceFeatureClassName;
            IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();

            //Validate the field names because you are converting between different workspace types.
            IFieldChecker fieldChecker = new FieldCheckerClass();
            IFields targetFeatureClassFields;
            IFields sourceFeatureClassFields = sourceFeatureClass.Fields;
            IEnumFieldError enumFieldError;
            // Most importantly set the input and validate workspaces!
            fieldChecker.InputWorkspace = sourceWorkspace;
            fieldChecker.ValidateWorkspace = targetWorkspace;
            fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);
            // Loop through the output fields to find the geomerty field
            IField geometryField;
            for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
            {
                if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                {
                    geometryField = targetFeatureClassFields.get_Field(i);
                    // Get the geometry field's geometry defenition
                    IGeometryDef geometryDef = geometryField.GeometryDef;
                    //Give the geometry definition a spatial index grid count and grid size
                    IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef;
                    targetFCGeoDefEdit.GridCount_2 = 1;
                    targetFCGeoDefEdit.set_GridSize(0, 0);
                    //Allow ArcGIS to determine a valid grid size for the data loaded
                    targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;
                    // we want to convert all of the features
                    IQueryFilter queryFilter = new QueryFilterClass();
                    queryFilter.WhereClause = "";
                    // Load the feature class
                    IFeatureDataConverter fctofc = new FeatureDataConverterClass();
                    IEnumInvalidObject enumErrors = fctofc.ConvertFeatureClass(sourceFeatureClassName, queryFilter, null, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0);
                    if (enumErrors.Next() == null)
                        change = true;
                    break;
                }
            }
            return change;
        }
        private static IFields CreateNewFields(fulcrumform form, IFields fields, ISpatialReference sr)
        {
            try
            {
                IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
                foreach (fulcrumelement element in form.elements)
                {
                    //!!! ToDo: Add data types as needed (numeric, etc)
                    if (element.data_name != "")
                    {
                        IField field = new FieldClass();
                        IFieldEdit2 fieldEdit = (IFieldEdit2)field;
                        switch (element.type)
                        {
                            case "Section":
                                //a Section is a whole different animal it will have sub elements (children) like so, element.elements
                                //!!!~but not dealing with them for now
                                fieldEdit.Name_2 = element.data_name;
                                fieldEdit.IsNullable_2 = true;
                                fieldEdit.AliasName_2 = element.label;
                                fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                                fieldEdit.Length_2 = 100;
                                // add field to field collection
                                fieldsEdit.AddField(field);
                                break;
                            case "ClassificationField":
                                fieldEdit.Name_2 = element.data_name;
                                fieldEdit.IsNullable_2 = true;
                                fieldEdit.AliasName_2 = element.label;
                                fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                                fieldEdit.Length_2 = 100;
                                fieldsEdit.AddField(field);
                                break;
                            case "ChoiceField":
                                fieldEdit.Name_2 = element.data_name;
                                fieldEdit.IsNullable_2 = true;
                                fieldEdit.AliasName_2 = element.label;
                                fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                                fieldEdit.Length_2 = 100;
                                fieldsEdit.AddField(field);
                                break;
                            case "TextField":
                                fieldEdit.Name_2 = element.data_name;
                                fieldEdit.IsNullable_2 = true;
                                fieldEdit.AliasName_2 = element.label;
                                fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                                fieldEdit.Length_2 = 255;
                                fieldsEdit.AddField(field);
                                break;
                            case "DateTimeField":
                                //if the name happens to be Date we need to override it
                                if (element.data_name == "date")
                                {
                                    fieldEdit.Name_2 = "record_date";
                                }
                                else
                                {
                                    fieldEdit.Name_2 = element.data_name;
                                }
                                fieldEdit.IsNullable_2 = true;
                                fieldEdit.AliasName_2 = element.label;
                                fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                                fieldEdit.Length_2 = 50;
                                fieldsEdit.AddField(field);
                                break;
                            case "PhotoField":
                                fieldEdit.Name_2 = photoFieldName;
                                fieldEdit.IsNullable_2 = true;
                                fieldEdit.AliasName_2 = element.label;
                                fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                                fieldEdit.Length_2 = 200;
                                //If we want to stuff the image in a raster field, here's a start
                                /*!!!
                                IRasterDef rasterDef = new RasterDefClass();
                                rasterDef.Description = "PictureField";
                                rasterDef.IsManaged = true;
                                rasterDef.IsRasterDataset = true;
                                //rasterDef.SpatialReference = sr;

                                 This is throwing an error
                                fieldEdit.RasterDef = rasterDef;
                                fieldEdit.Type_2 = esriFieldType.esriFieldTypeRaster;
                                 */
                                fieldsEdit.AddField(field);
                                break;
                            case "Label":
                                //skip it
                            default:
                                //a data type we haven't accounted for...
                                //don't create a field for it
                                break;
                        }
                        field = null;
                        fieldEdit = null;
                    }
                }
                fields = (IFields)fieldsEdit;

                // Use IFieldChecker to create a validated fields collection.
                IFieldChecker fieldChecker = new FieldCheckerClass();
                IEnumFieldError enumFieldError = null;
                IFields validatedFields = null;
                fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

                // The enumFieldError enumerator can be inspected at this point to determine
                // which fields were modified during validation.
                if (enumFieldError != null)
                {
                    enumFieldError.Reset();
                    IFieldError err = enumFieldError.Next();
                    while (!(err == null))
                    {
                        //!!!ToDo:
                        //we need to do something here cause the feature class will not be created with invalid fields
                        Console.WriteLine(err.FieldError + " at index " + err.FieldIndex);
                        err = enumFieldError.Next();
                    }
                }
                return validatedFields;
            }
            catch (Exception e)
            {
                string choke = e.Message;
                return null;
            }
        }
示例#44
0
        ////数据复制
        public IFeatureClass IFeatureDataConverter_ConvertFeatureClass(IWorkspace sourceWorkspace, IWorkspace targetWorkspace, string nameOfSourceFeatureClass, string nameOfTargetFeatureClass)
        {
            //create source workspace name
            IDataset       sourceWorkspaceDataset = (IDataset)sourceWorkspace;
            IWorkspaceName sourceWorkspaceName    = (IWorkspaceName)sourceWorkspaceDataset.FullName;
            //create source dataset name
            IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
            IDatasetName      sourceDatasetName      = (IDatasetName)sourceFeatureClassName;

            sourceDatasetName.WorkspaceName = sourceWorkspaceName;
            sourceDatasetName.Name          = nameOfSourceFeatureClass;
            //create target workspace name
            IDataset       targetWorkspaceDataset = (IDataset)targetWorkspace;
            IWorkspaceName targetWorkspaceName    = (IWorkspaceName)targetWorkspaceDataset.FullName;
            //create target dataset name
            IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
            IDatasetName      targetDatasetName      = (IDatasetName)targetFeatureClassName;

            targetDatasetName.WorkspaceName = targetWorkspaceName;
            targetDatasetName.Name          = nameOfTargetFeatureClass;
            //Open input Featureclass to get field definitions.
            ESRI.ArcGIS.esriSystem.IName sourceName = (ESRI.ArcGIS.esriSystem.IName)sourceFeatureClassName;
            IFeatureClass sourceFeatureClass        = (IFeatureClass)sourceName.Open();

            //Validate the field names because you are converting between different workspace types.
            IFieldChecker   fieldChecker = new FieldCheckerClass();
            IFields         targetFeatureClassFields;
            IFields         sourceFeatureClassFields = sourceFeatureClass.Fields;
            IEnumFieldError enumFieldError;

            // Most importantly set the input and validate workspaces!
            fieldChecker.InputWorkspace    = sourceWorkspace;
            fieldChecker.ValidateWorkspace = targetWorkspace;
            fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);
            // Loop through the output fields to find the geomerty field
            IField geometryField;

            for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
            {
                if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                {
                    geometryField = targetFeatureClassFields.get_Field(i);
                    // Get the geometry field's geometry defenition
                    IGeometryDef geometryDef = geometryField.GeometryDef;
                    //Give the geometry definition a spatial index grid count and grid size
                    IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef;
                    targetFCGeoDefEdit.GridCount_2 = 1;
                    targetFCGeoDefEdit.set_GridSize(0, 0);
                    //Allow ArcGIS to determine a valid grid size for the data loaded
                    targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;
                    // we want to convert all of the features
                    IQueryFilter queryFilter = new QueryFilterClass();
                    queryFilter.WhereClause = "";
                    // Load the feature class
                    IFeatureDataConverter fctofc     = new FeatureDataConverterClass();
                    IEnumInvalidObject    enumErrors = fctofc.ConvertFeatureClass(sourceFeatureClassName, queryFilter, null, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0);
                    break;
                }
            }

            //Open input Featureclass to get field definitions.
            ESRI.ArcGIS.esriSystem.IName targetName = (ESRI.ArcGIS.esriSystem.IName)targetFeatureClassName;
            return((IFeatureClass)targetName.Open());
        }
示例#45
0
        /// <summary>
        /// SDE要素类导出mdb
        /// </summary>
        /// <param name="sourceWorkspace">源工作空间</param>
        /// <param name="targetWorkspace">目标工作空间</param>
        /// <param name="nameOfSourceFeatureClass">源要素类名</param>
        /// <param name="nameOfTargetFeatureClass">目标要素类名</param>
        /// <param name="queryFilter"></param>
        /// <returns></returns>
        private bool ConvertFeatureClass(IWorkspace sourceWorkspace, IWorkspace targetWorkspace, string nameOfSourceFeatureClass, string nameOfTargetFeatureClass)
        {
            //创建一个源数据的工作空间的name
            IDataset       sourceWorkspaceDataset = (IDataset)sourceWorkspace;
            IWorkspaceName sourceWorkspaceName    = (IWorkspaceName)sourceWorkspaceDataset.FullName;

            //创建源数据Name作为转换参数
            IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
            IDatasetName      sourceDatasetName      = (IDatasetName)sourceFeatureClassName;

            sourceDatasetName.WorkspaceName = sourceWorkspaceName;
            sourceDatasetName.Name          = nameOfSourceFeatureClass;

            //创建目标(导出)数据空间的name
            IDataset       targetWorkspaceDataset = (IDataset)targetWorkspace;
            IWorkspaceName targetWorkspaceName    = (IWorkspaceName)targetWorkspaceDataset.FullName;

            //创建目标数据Name作为转换参数
            IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
            IDatasetName      targetDatasetName      = (IDatasetName)targetFeatureClassName;

            targetDatasetName.WorkspaceName = targetWorkspaceName;

            //这个命名也很重要,如果是mdb,那么这个命名在数据库中必须是本来不存在的(当然你可以先清空数据库)
            targetDatasetName.Name = nameOfTargetFeatureClass;

            //根据FetureClassName打开数据
            ESRI.ArcGIS.esriSystem.IName sourceName = (ESRI.ArcGIS.esriSystem.IName)sourceFeatureClassName;
            IFeatureClass sourceFeatureClass        = (IFeatureClass)sourceName.Open();

            //在两个不同的工作空间转换数据要检查字段的有效性
            //一些检查有效性的参数
            IFieldChecker   fieldChecker = new FieldCheckerClass();
            IFields         targetFeatureClassFields;
            IFields         sourceFeatureClassFields = sourceFeatureClass.Fields;
            IEnumFieldError enumFieldError;

            //设置检查有效性的源数据工作空间
            fieldChecker.InputWorkspace    = sourceWorkspace;
            fieldChecker.ValidateWorkspace = targetWorkspace;
            fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);

            //通过输出字段循环找出几何字段
            IField geometryField;

            //遍历字段
            for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
            {
                //找到定义几何要素类型的字段
                if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                {
                    //获取当前字段
                    geometryField = targetFeatureClassFields.get_Field(i);
                    //编辑几何要素类型字段
                    IGeometryDef     geometryDef        = geometryField.GeometryDef;
                    IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef;
                    targetFCGeoDefEdit.GridCount_2 = 1;
                    targetFCGeoDefEdit.set_GridSize(0, 0);
                    //保证空间参考      SpatialReference_2属性字段才是可写的,SpatialReference属性只可读
                    targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;
                    //开始转换
                    IFeatureDataConverter myConvert = new FeatureDataConverterClass();
                    myConvert.ConvertFeatureClass(sourceFeatureClassName, null, null, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0);
                    return(true);
                }
            }
            return(false);
        }
示例#46
0
        /// <summary>
        /// 复制源图层到目标dataset中的目标图层
        /// </summary>
        /// <param name="sourceWorkspaceDataset">源图层集</param>
        /// <param name="targetWorkspaceDataset">目标图层集</param>
        /// <param name="sourceFeatureClass">源图层</param>
        /// <param name="nameOfTargetFeatureClass">待创建的图层名</param>
        public static IFeatureClass ConvertFeatureClass(IDataset sourceWorkspaceDataset, IDataset targetWorkspaceDataset,
                                                        IFeatureClass sourceFeatureClass,
                                                        string nameOfTargetFeatureClass)
        {
            IFeatureClass TragetFeatureClass = null;
            try
            {
                IFeatureClassName nameOfSourceFeatureClass =
                    ((IDataset)sourceFeatureClass).FullName as IFeatureClassName;

                IDatasetName pSourceDsName = (IDatasetName)sourceWorkspaceDataset.FullName;
                IDatasetName pTargetDsName = (IDatasetName)targetWorkspaceDataset.FullName;

                IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
                targetFeatureClassName.FeatureDatasetName = pTargetDsName;
                IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName;
                targetDatasetName.Name = nameOfTargetFeatureClass;

                //Validate the field names because you are converting between different workspace types.
                IFieldChecker fieldChecker = new FieldCheckerClass();
                IFields targetFeatureClassFields;
                IFields sourceFeatureClassFields = sourceFeatureClass.Fields;
                IEnumFieldError enumFieldError;
                // Most importantly set the input and validate workspaces!

                fieldChecker.InputWorkspace = sourceWorkspaceDataset.Workspace;
                fieldChecker.ValidateWorkspace = targetWorkspaceDataset.Workspace;
                fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);
                // Loop through the output fields to find the geomerty field
                IField geometryField;
                for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
                {
                    if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        geometryField = targetFeatureClassFields.get_Field(i);
                        // Get the geometry field's geometry defenition
                        IGeometryDef geometryDef = geometryField.GeometryDef;
                        //Give the geometry definition a spatial index grid count and grid size
                        IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef;
                        //targetFCGeoDefEdit.GridCount_2 = 1;
                        //targetFCGeoDefEdit.set_GridSize(0, 0);
                        //Allow ArcGIS to determine a valid grid size for the data loaded
                        targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;
                        // we want to convert all of the features
                        IQueryFilter queryFilter = new QueryFilterClass();
                        queryFilter.WhereClause = "";
                        // Load the feature class
                        IFeatureDataConverter fctofc = new FeatureDataConverterClass();

                        IEnumInvalidObject enumErrors =
                            fctofc.ConvertFeatureClass(nameOfSourceFeatureClass, queryFilter,
                                                       pTargetDsName as IFeatureDatasetName, targetFeatureClassName,
                                                       geometryDef, targetFeatureClassFields, "", 1000, 0);
                        break;
                    }
                }

                string strTargetFtCls = ((IDatasetName)targetFeatureClassName).Name;
                TragetFeatureClass =
                    ((IFeatureWorkspace)targetWorkspaceDataset.Workspace).OpenFeatureClass(strTargetFtCls);
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                return null;
            }
            return TragetFeatureClass;
        }
        private static ITable CreateTable(IWorkspace2 workspace, string tableName, IFields fields)
        {
            UID uid = new UIDClass {Value = "esriGeoDatabase.Object"};

            if (workspace == null) return null;

            IFeatureWorkspace featWorkspace = (IFeatureWorkspace) workspace;

            if (workspace.NameExists[esriDatasetType.esriDTTable, tableName])
            {
                using (ComReleaser releaser = new ComReleaser())
                {
                    ITable table = featWorkspace.OpenTable(tableName);
                    releaser.ManageLifetime(table);
                    ((IDataset) table).Delete();
                }
            }


            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null;
            fieldChecker.ValidateWorkspace = workspace as IWorkspace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            return featWorkspace.CreateTable(tableName, validatedFields, uid, null, string.Empty);
        }
示例#48
0
        /// <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);
        }
        /// <summary>
        /// Creates the field collection for a new feature class or standalone table.
        /// </summary>
        /// <param name="bSpatial">True if the new fields collection is for a feature class, false if a table.</param>
        /// <param name="bHasZ">True if the geometry field of the fields collection to be created is to be Z aware.</param>
        /// <param name="bHasM">True if the geometry field of the fields collection to be created is to be M aware.</param>
        /// <param name="oWorkspace">The workspace in which a new feature class will be created from the fields collection.</param>
        /// <param name="geomType">The geometry type of the feature class to be created from the new fields collection.</param>
        /// <param name="aFldLengths">An array of field lengths of the fields collection to be created.</param>
        /// <param name="aFldNames">An array of field names of the fields collection to be created.</param>
        /// <param name="aFldAliases">An array of field aliases of the fields collection to be created.</param>
        /// <param name="aFldTypes">An array of field types of the fields collection to be created.</param>
        /// <param name="spatialReference">The coordinate system to be assigned to the new feature class.</param>
        /// <returns>Returns the new field collection. Throws an error if no field collection can be created.</returns>
        private IFields CreateFieldsCollection(bool hasGeom, bool hasZ, bool hasM, object outWorkspace,
            esriGeometryType geometryType, int[] fieldLengths, string[] fieldNames, string[] fieldAliases,
            esriFieldType[] fieldTypes, bool[] fieldNullable, ISpatialReference spatialReference)
        {
            if ((hasGeom) && (outWorkspace is IWorkspace) && (spatialReference == null))
                throw new Exception("Spatial reference must be defined for standalone feature classes");

            IWorkspace outputWorkspace = null;
            if (outWorkspace is IWorkspace)
            {
                outputWorkspace = outWorkspace as IWorkspace;
            }
            else if (outWorkspace is IFeatureDataset)
            {
                outputWorkspace = ((IDataset)((IFeatureDataset)outWorkspace)).Workspace;
            }

            IFields fields = new FieldsClass();
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
            if (hasGeom)
            {
                IGeometryDef geometryDef = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.GeometryType_2 = geometryType;
                geometryDefEdit.GridCount_2 = 1;
                geometryDefEdit.set_GridSize(0, 0); // (0, 0.5);
                geometryDefEdit.AvgNumPoints_2 = 2;
                geometryDefEdit.HasM_2 = hasM;
                geometryDefEdit.HasZ_2 = hasZ;
                if (outWorkspace is IWorkspace) geometryDefEdit.SpatialReference_2 = spatialReference;
                IField fieldOID = new FieldClass();
                IFieldEdit fieldEditOID = (IFieldEdit)fieldOID;
                fieldEditOID.Name_2 = "OBJECTID";
                fieldEditOID.AliasName_2 = "OBJECTID";
                fieldEditOID.Type_2 = esriFieldType.esriFieldTypeOID;
                fieldsEdit.AddField(fieldOID);
                IField fieldShape = new FieldClass();
                IFieldEdit fieldEditShape = (IFieldEdit)fieldShape;
                fieldEditShape.Name_2 = "SHAPE";
                fieldEditShape.AliasName_2 = "SHAPE";
                fieldEditShape.Type_2 = esriFieldType.esriFieldTypeGeometry;
                fieldEditShape.GeometryDef_2 = geometryDef;
                fieldsEdit.AddField(fieldShape);
            }
            else
            {
                IField fieldOID = new FieldClass();
                IFieldEdit fieldEditOID = (IFieldEdit)fieldOID;
                fieldEditOID.Name_2 = "OBJECTID";
                fieldEditOID.AliasName_2 = "OBJECTID";
                fieldEditOID.Type_2 = esriFieldType.esriFieldTypeOID;
                fieldsEdit.AddField(fieldOID);
            }

            if (fieldAliases == null) fieldAliases = fieldNames;

            IField fieldAtt;
            IFieldEdit fieldEditAtt;
            for (int i = 0; i < fieldTypes.Length; i++)
            {
                if (String.IsNullOrEmpty(fieldNames[i]))
                    throw new Exception(String.Format("Error creating field {0}", i));
                if ((fieldTypes[i] == esriFieldType.esriFieldTypeOID) ||
                    (fieldTypes[i] == esriFieldType.esriFieldTypeGeometry))
                    continue;
                fieldAtt = new FieldClass();
                fieldEditAtt = (IFieldEdit)fieldAtt;
                fieldEditAtt.Name_2 = fieldNames[i];
                if (!String.IsNullOrEmpty(fieldAliases[i]))
                    fieldEditAtt.AliasName_2 = fieldAliases[i];
                fieldEditAtt.Type_2 = fieldTypes[i];
                fieldEditAtt.Editable_2 = true;
                fieldEditAtt.Required_2 = false;
                fieldEditAtt.IsNullable_2 = fieldNullable[i];// true;
                if (fieldTypes[i] == esriFieldType.esriFieldTypeString)
                {
                    //if ((fieldLengths[i] == -1) || ((fieldLengths[i] > 0) && (fieldLengths[i] < 256)))
                    fieldEditAtt.Length_2 = fieldLengths[i];
                    //else
                    //    fieldEditAtt.Length_2 = 255;
                }
                fieldsEdit.AddField(fieldAtt);
            }
            IFieldChecker fldChk = new FieldCheckerClass();
            fldChk.ValidateWorkspace = outputWorkspace;

            IFields outFields;
            IEnumFieldError fieldErrors;
            fldChk.Validate(fields, out fieldErrors, out outFields);
            return outFields;
        }
示例#50
0
        internal esriFieldNameErrorType ValidateFieldName(string name)
        {
            IFeatureClass featureClass = GetFeatureClass();
            if (featureClass == null)
                return esriFieldNameErrorType.esriNoFieldError;

            IFields fields = featureClass.Fields;
            IWorkspace workspace = ((IDataset)featureClass).Workspace;
            IField newField = new FieldClass();
            ((IFieldEdit)newField).Name_2 = name;
            ((IFieldsEdit)fields).AddField(newField);

            IFieldChecker fieldChecker = new FieldCheckerClass();
            fieldChecker.ValidateWorkspace = workspace;

            // Validate the fields.
            IEnumFieldError enumFieldError;
            IFields validatedFields;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);
            ((IFieldsEdit)fields).DeleteField(newField);
            if (enumFieldError == null)
                return esriFieldNameErrorType.esriNoFieldError;
            // Display the field errors.
            enumFieldError.Reset();
            IFieldError fieldError = enumFieldError.Next();
            while (fieldError != null)
            {
                if (fieldError.FieldIndex == fields.FieldCount)
                    return fieldError.FieldError;
            }
            return esriFieldNameErrorType.esriNoFieldError;
        }
示例#51
0
        public static void Project(IFeatureClass ifeatureClass_0, ISpatialReference ispatialReference_0,
                                   IWorkspace iworkspace_0, string string_0, double double_0)
        {
            string                str2;
            double                num3;
            double                num4;
            double                num5;
            double                num6;
            IEnumFieldError       error;
            IFields               fields2;
            IWorkspace            workspace = ((IDataset)ifeatureClass_0).Workspace;
            IFeatureDataConverter converter = new FeatureDataConverterClass();
            IWorkspaceName        name      = new WorkspaceNameClass
            {
                ConnectionProperties   = workspace.ConnectionProperties,
                WorkspaceFactoryProgID = workspace.WorkspaceFactory.GetClassID().Value.ToString()
            };
            IWorkspaceName name2 = new WorkspaceNameClass();

            new PropertySetClass();
            name2.ConnectionProperties   = iworkspace_0.ConnectionProperties;
            name2.WorkspaceFactoryProgID = iworkspace_0.WorkspaceFactory.GetClassID().Value.ToString();
            IDatasetName name3     = new FeatureClassNameClass();
            string       aliasName = ifeatureClass_0.AliasName;
            int          index     = aliasName.LastIndexOf(".");

            if (index != -1)
            {
                aliasName = aliasName.Substring(index + 1);
            }
            name3.Name          = aliasName;
            name3.WorkspaceName = name;
            IDatasetName name4 = new FeatureClassNameClass
            {
                WorkspaceName = name2
            };
            IFieldChecker checker = new FieldCheckerClass
            {
                ValidateWorkspace = iworkspace_0
            };

            string[] strArray = string_0.Split(new char[] { '.' });
            string_0 = strArray[strArray.Length - 1] + "_Project";
            checker.ValidateTableName(string_0, out str2);
            string str3 = str2;
            int    num2 = 1;

            if ((iworkspace_0.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace) ||
                (iworkspace_0.Type == esriWorkspaceType.esriLocalDatabaseWorkspace))
            {
                while (((IWorkspace2)iworkspace_0).get_NameExists(esriDatasetType.esriDTFeatureClass, str3))
                {
                    str3 = str2 + "_" + num2.ToString();
                    num2++;
                }
            }
            else if (iworkspace_0.Type == esriWorkspaceType.esriFileSystemWorkspace)
            {
                while (File.Exists(str3 + ".shp"))
                {
                    str3 = str2 + "_" + num2.ToString();
                    num2++;
                }
            }
            name4.Name = str3;
            IFields inputField = new FieldsClass();

            index = ifeatureClass_0.Fields.FindField(ifeatureClass_0.ShapeFieldName);
            IField            field            = ifeatureClass_0.Fields.get_Field(index);
            IGeometryDef      geometryDef      = field.GeometryDef;
            ISpatialReference spatialReference = geometryDef.SpatialReference;

            ispatialReference_0.GetDomain(out num3, out num4, out num5, out num6);
            ((IGeometryDefEdit)geometryDef).GridCount_2 = 1;
            ((IGeometryDefEdit)geometryDef).set_GridSize(0, double_0);
            ((IGeometryDefEdit)geometryDef).SpatialReference_2 = ispatialReference_0;
            ((IFieldEdit)field).GeometryDef_2 = geometryDef;
            for (int i = 0; i < ifeatureClass_0.Fields.FieldCount; i++)
            {
                if (i == index)
                {
                    ((IFieldsEdit)inputField).AddField(field);
                }
                else
                {
                    IField field2 = ifeatureClass_0.Fields.get_Field(i);
                    ((IFieldsEdit)inputField).AddField(field2);
                }
            }
            checker.Validate(inputField, out error, out fields2);
            if (m_pfrm != null)
            {
                m_pfrm.FeatureProgress = converter;
            }
            try
            {
                converter.ConvertFeatureClass((IFeatureClassName)name3, null, null, (IFeatureClassName)name4,
                                              geometryDef, fields2, "", 1000, 0);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
        // create table in file geodatabase
        #region "create table in file geodatabase"
        public static ESRI.ArcGIS.Geodatabase.ITable CreateTable(String tableName, UID classExtensionUID, 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 = "OBJECTID";
            oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            fieldsEdit.AddField(oidField);

            // Create a text field called "ADDRSYS_L" for the fields collection.
            IField     addrSysLField     = new FieldClass();
            IFieldEdit addrSysLFieldEdit = (IFieldEdit)addrSysLField;

            addrSysLFieldEdit.Name_2   = "ADDRSYS_L";
            addrSysLFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            addrSysLFieldEdit.Length_2 = 30;
            fieldsEdit.AddField(addrSysLField);

            // Create a text field called "ADDRSYS_R" for the fields collection.
            IField     addrSysRField     = new FieldClass();
            IFieldEdit addrSysRFieldEdit = (IFieldEdit)addrSysRField;

            addrSysRFieldEdit.Name_2   = "ADDRSYS_R";
            addrSysRFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            addrSysRFieldEdit.Length_2 = 30;
            fieldsEdit.AddField(addrSysRField);

            // Create a text field called "FROMADDR_L" for the fields collection.
            IField     rangeL_Ffield     = new FieldClass();
            IFieldEdit rangeL_FfieldEdit = (IFieldEdit)rangeL_Ffield;

            rangeL_FfieldEdit.Name_2      = "FROMADDR_L";
            rangeL_FfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeL_FfieldEdit.Precision_2 = 38;
            rangeL_FfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeL_Ffield);

            // Create a text field called "TOADDR_L" for the fields collection.
            IField     rangeL_Tfield     = new FieldClass();
            IFieldEdit rangeL_TfieldEdit = (IFieldEdit)rangeL_Tfield;

            rangeL_TfieldEdit.Name_2      = "TOADDR_L";
            rangeL_TfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeL_TfieldEdit.Precision_2 = 38;
            rangeL_TfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeL_Tfield);

            // Create a text field called "FROMADDR_R" for the fields collection.
            IField     rangeR_Ffield     = new FieldClass();
            IFieldEdit rangeR_FfieldEdit = (IFieldEdit)rangeR_Ffield;

            rangeR_FfieldEdit.Name_2      = "FROMADDR_R";
            rangeR_FfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeR_FfieldEdit.Precision_2 = 38;
            rangeR_FfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeR_Ffield);

            // Create a text field called "TOADDR_R" for the fields collection.
            IField     rangeR_Tfield     = new FieldClass();
            IFieldEdit rangeR_TfieldEdit = (IFieldEdit)rangeR_Tfield;

            rangeR_TfieldEdit.Name_2      = "TOADDR_R";
            rangeR_TfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeR_TfieldEdit.Precision_2 = 38;
            rangeR_TfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeR_Tfield);

            // Create a text field called "PREDIR" for the fields collection.
            IField     predirField     = new FieldClass();
            IFieldEdit predirFieldEdit = (IFieldEdit)predirField;

            predirFieldEdit.Name_2   = "PREDIR";
            predirFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            predirFieldEdit.Length_2 = 1;
            fieldsEdit.AddField(predirField);

            // Create a text field called "NAME" for the fields collection.
            IField     nameField     = new FieldClass();
            IFieldEdit nameFieldEdit = (IFieldEdit)nameField;

            nameFieldEdit.Name_2   = "NAME";
            nameFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            nameFieldEdit.Length_2 = 30;
            fieldsEdit.AddField(nameField);

            // Create a text field called "POSTTYPE" for the fields collection.
            IField     streettypeField     = new FieldClass();
            IFieldEdit streettypeFieldEdit = (IFieldEdit)streettypeField;

            streettypeFieldEdit.Name_2   = "POSTTYPE";
            streettypeFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            streettypeFieldEdit.Length_2 = 4;
            fieldsEdit.AddField(streettypeField);

            // Create a text field called "POSTDIR" for the fields collection.
            IField     sufdirField     = new FieldClass();
            IFieldEdit sufdirFieldEdit = (IFieldEdit)sufdirField;

            sufdirFieldEdit.Name_2   = "POSTDIR";
            sufdirFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            sufdirFieldEdit.Length_2 = 2;
            fieldsEdit.AddField(sufdirField);

            // Create a text field called "ZIPCODE_L" for the fields collection.
            IField     zipleftField     = new FieldClass();
            IFieldEdit zipleftFieldEdit = (IFieldEdit)zipleftField;

            zipleftFieldEdit.Name_2   = "ZIPCODE_L";
            zipleftFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            zipleftFieldEdit.Length_2 = 5;
            fieldsEdit.AddField(zipleftField);

            // Create a text field called "ZIPCODE_R" for the fields collection.
            IField     ziprightField     = new FieldClass();
            IFieldEdit ziprightFieldEdit = (IFieldEdit)ziprightField;

            ziprightFieldEdit.Name_2   = "ZIPCODE_R";
            ziprightFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            ziprightFieldEdit.Length_2 = 5;
            fieldsEdit.AddField(ziprightField);

            // Create a text field called "GLOBALID_SGID" for the fields collection - to join back to the feature class or sgid.
            IField     globalidField     = new FieldClass();
            IFieldEdit globalidFieldEdit = (IFieldEdit)globalidField;

            globalidFieldEdit.Name_2   = "GLOBALID_SGID";
            globalidFieldEdit.Type_2   = esriFieldType.esriFieldTypeString; // use string and not the globalid type b/c it might that might assign it's own unique global id and this is for joinging back to sgid
            globalidFieldEdit.Length_2 = 50;
            fieldsEdit.AddField(globalidField);

            // Use IFieldChecker to create a validated fields collection.
            IFieldChecker   fieldChecker    = new FieldCheckerClass();
            IEnumFieldError enumFieldError  = null;
            IFields         validatedFields = null;

            fieldChecker.ValidateWorkspace = (IWorkspace)featureWorkspace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            // 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).
            ESRI.ArcGIS.Geodatabase.ITable arcTable = featureWorkspace.CreateTable(tableName, validatedFields, null, classExtensionUID, "");

            return(arcTable);
        }
示例#53
0
        /// <summary>
        /// 将GDB的数据入到SDE中 xisheng 20110919
        /// </summary>
        private void ImportGDBToSDE(string file, string outfilename, out int featurecount)
        {
            m_success = false;//初始化
            try
            {
                string filepath = file.Substring(0, file.LastIndexOf("---"));
                string filename = file.Substring(file.LastIndexOf("-") + 1);

                //打开mdb文件所在的工作空间
                ESRI.ArcGIS.Geodatabase.IWorkspaceFactory wf = new FileGDBWorkspaceFactory();
                IFeatureWorkspace pFeatureWorkspaceGDB       = wf.OpenFromFile(@filepath, 0) as IFeatureWorkspace;
                IWorkspace        pWorkspaceGDB = pFeatureWorkspaceGDB as IWorkspace;
                // 创建源工作空间名称
                IDataset       sourceWorkspaceDataset = (IDataset)pFeatureWorkspaceGDB;
                IWorkspaceName sourceWorkspaceName    = (IWorkspaceName)sourceWorkspaceDataset.FullName;

                //创建源数据集名称
                //IFeatureClassName sourceFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName;
                IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
                IDatasetName      sourceDatasetName      = (IDatasetName)sourceFeatureClassName;
                sourceDatasetName.WorkspaceName = sourceWorkspaceName;
                sourceDatasetName.Name          = filename;

                //打开存在的工作空间,作为导入的空间;
                IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pTargetworkspace;

                //创建目标工作空间名称
                IDataset        targetWorkspaceDataset = (IDataset)pTargetworkspace;
                IWorkspaceName  targetWorkspaceName    = (IWorkspaceName)targetWorkspaceDataset.FullName;
                IWorkspace2     pWorkspace2            = pTargetworkspace as IWorkspace2;
                IFeatureDataset tmpfeaturedataset;
                //创建目标数据集名称
                // IFeatureClassName targetFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName;
                //判断要素是否存在,若存在将删除源文件
                if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureDataset, textBox.Text))
                {
                    tmpfeaturedataset = pFeatureWorkspace.OpenFeatureDataset(textBox.Text);
                    if (text_prj.Text != "")
                    {
                        IGeoDatasetSchemaEdit pgeodataset = tmpfeaturedataset as IGeoDatasetSchemaEdit;
                        if (pgeodataset.CanAlterSpatialReference)
                        {
                            pgeodataset.AlterSpatialReference(GetSpatialReferenceformFile(text_prj.Text));
                        }
                    }
                }
                else
                {
                    tmpfeaturedataset = CreateFeatureDataset(pTargetworkspace as IFeatureWorkspace, textBox.Text, text_prj.Text);
                }
                if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, outfilename))
                {
                    IFeatureClass tmpfeatureclass;
                    tmpfeatureclass = pFeatureWorkspace.OpenFeatureClass(outfilename);
                    IDataset tempset = tmpfeatureclass as IDataset;
                    tempset.Delete();
                }

                IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
                IDatasetName      targetDatasetName      = (IDatasetName)targetFeatureClassName;
                targetDatasetName.WorkspaceName = targetWorkspaceName;
                targetDatasetName.Name          = outfilename;
                //目标数据集
                IFeatureDatasetName outfeaturedatasetname = tmpfeaturedataset.FullName as IFeatureDatasetName;


                //打开输入的要素类以得到字段定义
                ESRI.ArcGIS.esriSystem.IName sourceName = (ESRI.ArcGIS.esriSystem.IName)sourceFeatureClassName;
                IFeatureClass sourceFeatureClass        = (IFeatureClass)sourceName.Open();//打开源要素类

                //验证字段名称,因为你正在不同类型的工作空间之间进行数据转换
                //IFieldChecker fieldChecker = serverContext.CreateObject("esriGeoDatabase.FieldChecker") as IFieldChecker;
                IFieldChecker   fieldChecker             = new FieldCheckerClass();
                IFields         sourceFeatureClassFields = sourceFeatureClass.Fields;
                IFields         targetFeatureClassFields;
                IEnumFieldError enumFieldError;

                //最重要的设置输入和验证工作空间
                fieldChecker.InputWorkspace    = pWorkspaceGDB;
                fieldChecker.ValidateWorkspace = pTargetworkspace;
                fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);

                //遍历所有输出字段找到几何字段
                IField geometryField;
                for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
                {
                    if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        geometryField = targetFeatureClassFields.get_Field(i);
                        //得到几何字段的几何定义
                        IGeometryDef geometryDef = geometryField.GeometryDef;
                        //赋予几何定义一个空间索引格网数目和格网大小值
                        IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef;
                        targetFCGeoDefEdit.GridCount_2 = 1;
                        targetFCGeoDefEdit.set_GridSize(0, 0);
                        //允许ArcGIS为数据加载确定一个有效的格网大小
                        targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;
                        //转换要素类中所有的要素
                        //IQueryFilter queryFilter = serverContext.CreateObject("esriGeoDatabase.QueryFilter") as IQueryFilter; ;
                        QueryFilter queryFilter = new QueryFilterClass();
                        queryFilter.WhereClause = "";
                        //加载要素类
                        //IFeatureDataConverter fctofc = serverContext.CreateObject("esriGeoDatabase.FeatureDataConverter") as IFeatureDataConverter;

                        IFeatureDataConverter fctofc     = new FeatureDataConverterClass();
                        IEnumInvalidObject    enumErrors = fctofc.ConvertFeatureClass(sourceFeatureClassName, queryFilter, outfeaturedatasetname, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0);
                    }
                }
                featurecount = sourceFeatureClass.FeatureCount(null);
                m_success    = true;
            }
            catch (Exception ee) { m_success = false; m_strErr = ee.Message; featurecount = 0; }
        }
        // create feature class in file geodatabase
        #region "create feature class in file geodatabase"
        public static ESRI.ArcGIS.Geodatabase.IFeatureClass CreateFeatureClass(String featureClassName, UID classExtensionUID, IFeatureWorkspace featureWorkspace)
        {
            // check if the fc exist, if so rename it



            // Create a fields collection for the feature class.
            IFields     fields     = new FieldsClass();
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

            // Add an object ID field to the fields collection. This is mandatory for feature classes.
            IField     oidField     = new FieldClass();
            IFieldEdit oidFieldEdit = (IFieldEdit)oidField;

            oidFieldEdit.Name_2 = "OBJECTID";
            oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            fieldsEdit.AddField(oidField);

            // Create a geometry definition (and spatial reference) for the feature class.
            IGeometryDef     geometryDef     = new GeometryDefClass();
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;

            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
            ISpatialReferenceFactory    spatialReferenceFactory    = new SpatialReferenceEnvironmentClass();
            ISpatialReference           spatialReference           = spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_12N);
            ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;

            spatialReferenceResolution.ConstructFromHorizon();
            ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;

            spatialReferenceTolerance.SetDefaultXYTolerance();
            geometryDefEdit.SpatialReference_2 = spatialReference;

            // Add a geometry field to the fields collection. This is where the geometry definition is applied.
            IField     geometryField     = new FieldClass();
            IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField;

            geometryFieldEdit.Name_2        = "Shape";
            geometryFieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
            geometryFieldEdit.GeometryDef_2 = geometryDef;
            fieldsEdit.AddField(geometryField);

            // Create a text field called "ADDRSYS_L" for the fields collection.
            IField     addrSysLField     = new FieldClass();
            IFieldEdit addrSysLFieldEdit = (IFieldEdit)addrSysLField;

            addrSysLFieldEdit.Name_2   = "ADDRSYS_L";
            addrSysLFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            addrSysLFieldEdit.Length_2 = 30;
            fieldsEdit.AddField(addrSysLField);

            // Create a text field called "ADDRSYS_R" for the fields collection.
            IField     addrSysRField     = new FieldClass();
            IFieldEdit addrSysRFieldEdit = (IFieldEdit)addrSysRField;

            addrSysRFieldEdit.Name_2   = "ADDRSYS_R";
            addrSysRFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            addrSysRFieldEdit.Length_2 = 30;
            fieldsEdit.AddField(addrSysRField);


            // Create a text field called "FROMADDR_L" for the fields collection.
            IField     rangeL_Ffield     = new FieldClass();
            IFieldEdit rangeL_FfieldEdit = (IFieldEdit)rangeL_Ffield;

            rangeL_FfieldEdit.Name_2      = "FROMADDR_L";
            rangeL_FfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeL_FfieldEdit.Precision_2 = 38;
            rangeL_FfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeL_Ffield);

            // Create a text field called "TOADDR_L" for the fields collection.
            IField     rangeL_Tfield     = new FieldClass();
            IFieldEdit rangeL_TfieldEdit = (IFieldEdit)rangeL_Tfield;

            rangeL_TfieldEdit.Name_2      = "TOADDR_L";
            rangeL_TfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeL_TfieldEdit.Precision_2 = 38;
            rangeL_TfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeL_Tfield);

            // Create a text field called "FROMADDR_R" for the fields collection.
            IField     rangeR_Ffield     = new FieldClass();
            IFieldEdit rangeR_FfieldEdit = (IFieldEdit)rangeR_Ffield;

            rangeR_FfieldEdit.Name_2      = "FROMADDR_R";
            rangeR_FfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeR_FfieldEdit.Precision_2 = 38;
            rangeR_FfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeR_Ffield);

            // Create a text field called "TOADDR_R" for the fields collection.
            IField     rangeR_Tfield     = new FieldClass();
            IFieldEdit rangeR_TfieldEdit = (IFieldEdit)rangeR_Tfield;

            rangeR_TfieldEdit.Name_2      = "TOADDR_R";
            rangeR_TfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeR_TfieldEdit.Precision_2 = 38;
            rangeR_TfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeR_Tfield);

            // Create a text field called "PREDIR" for the fields collection.
            IField     predirField     = new FieldClass();
            IFieldEdit predirFieldEdit = (IFieldEdit)predirField;

            predirFieldEdit.Name_2   = "PREDIR";
            predirFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            predirFieldEdit.Length_2 = 1;
            fieldsEdit.AddField(predirField);

            // Create a text field called "NAME" for the fields collection.
            IField     nameField     = new FieldClass();
            IFieldEdit nameFieldEdit = (IFieldEdit)nameField;

            nameFieldEdit.Name_2   = "NAME";
            nameFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            nameFieldEdit.Length_2 = 30;
            fieldsEdit.AddField(nameField);

            // Create a text field called "POSTTYPE" for the fields collection.
            IField     streettypeField     = new FieldClass();
            IFieldEdit streettypeFieldEdit = (IFieldEdit)streettypeField;

            streettypeFieldEdit.Name_2   = "POSTTYPE";
            streettypeFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            streettypeFieldEdit.Length_2 = 4;
            fieldsEdit.AddField(streettypeField);

            // Create a text field called "POSTDIR" for the fields collection.
            IField     sufdirField     = new FieldClass();
            IFieldEdit sufdirFieldEdit = (IFieldEdit)sufdirField;

            sufdirFieldEdit.Name_2   = "POSTDIR";
            sufdirFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            sufdirFieldEdit.Length_2 = 2;
            fieldsEdit.AddField(sufdirField);

            // Create a text field called "ZIPCODE_L" for the fields collection.
            IField     zipleftField     = new FieldClass();
            IFieldEdit zipleftFieldEdit = (IFieldEdit)zipleftField;

            zipleftFieldEdit.Name_2   = "ZIPCODE_L";
            zipleftFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            zipleftFieldEdit.Length_2 = 5;
            fieldsEdit.AddField(zipleftField);

            // Create a text field called "ZIPCODE_R" for the fields collection.
            IField     ziprightField     = new FieldClass();
            IFieldEdit ziprightFieldEdit = (IFieldEdit)ziprightField;

            ziprightFieldEdit.Name_2   = "ZIPCODE_R";
            ziprightFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            ziprightFieldEdit.Length_2 = 5;
            fieldsEdit.AddField(ziprightField);

            // Create a text field called "GLOBALID_SGID" for the fields collection - to join to the table or sgid.
            IField     globalidField     = new FieldClass();
            IFieldEdit globalidFieldEdit = (IFieldEdit)globalidField;

            globalidFieldEdit.Name_2   = "GLOBALID_SGID";
            globalidFieldEdit.Type_2   = esriFieldType.esriFieldTypeString; // use string and not the globalid type b/c it might that might assign it's own unique global id and this is for joinging back to sgid
            globalidFieldEdit.Length_2 = 50;
            fieldsEdit.AddField(globalidField);

            // Use IFieldChecker to create a validated fields collection.
            IFieldChecker   fieldChecker    = new FieldCheckerClass();
            IEnumFieldError enumFieldError  = null;
            IFields         validatedFields = null;

            fieldChecker.ValidateWorkspace = (IWorkspace)featureWorkspace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            // The enumFieldError enumerator can be inspected at this point to determine
            // which fields were modified during validation.

            // Create the feature class. Note that the CLSID parameter is null - this indicates to use the
            // default CLSID, esriGeodatabase.Feature (acceptable in most cases for feature classes).
            IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, null, classExtensionUID, esriFeatureType.esriFTSimple, "Shape", "");

            return(featureClass);
        }
示例#55
0
        ///<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;
        }
示例#56
0
        //创建featureclass
        private IFeatureClass CreateFeatureClass(string name, IFeatureClass pFeaCls, IFeatureDataset pFeaDataset, IFeatureWorkspace pWks)
        {
            UID uidCLSID  = null;
            UID uidCLSEXT = null;


            try
            {
                IObjectClassDescription pObjCls = null;
                if (uidCLSID == null)
                {
                    //esriGeometryType GeometryType;
                    uidCLSID = new UIDClass();
                    switch (pFeaCls.FeatureType)
                    {
                    case (esriFeatureType.esriFTSimple):
                        uidCLSID.Value = "{52353152-891A-11D0-BEC6-00805F7C4268}";
                        break;

                    case (esriFeatureType.esriFTSimpleJunction):
                        //GeometryType = esriGeometryType.esriGeometryPoint;
                        uidCLSID.Value = "{CEE8D6B8-55FE-11D1-AE55-0000F80372B4}";
                        break;

                    case (esriFeatureType.esriFTComplexJunction):
                        uidCLSID.Value = "{DF9D71F4-DA32-11D1-AEBA-0000F80372B4}";
                        break;

                    case (esriFeatureType.esriFTSimpleEdge):
                        //GeometryType = esriGeometryType.esriGeometryPolyline;
                        uidCLSID.Value = "{E7031C90-55FE-11D1-AE55-0000F80372B4}";
                        break;

                    case (esriFeatureType.esriFTComplexEdge):
                        //GeometryType = esriGeometryType.esriGeometryPolyline;
                        uidCLSID.Value = "{A30E8A2A-C50B-11D1-AEA9-0000F80372B4}";
                        break;

                    case (esriFeatureType.esriFTAnnotation):
                        //GeometryType = esriGeometryType.esriGeometryPolygon;
                        uidCLSID.Value = "{E3676993-C682-11D2-8A2A-006097AFF44E}";
                        break;

                    case (esriFeatureType.esriFTDimension):
                        //GeometryType = esriGeometryType.esriGeometryPolygon;
                        uidCLSID.Value = "{496764FC-E0C9-11D3-80CE-00C04F601565}";
                        break;
                    }
                }

                // 设置 uidCLSEXT (if Null)
                if (uidCLSEXT == null)
                {
                    switch (pFeaCls.FeatureType)
                    {
                    case (esriFeatureType.esriFTAnnotation):
                        uidCLSEXT       = new UIDClass();
                        uidCLSEXT.Value = "{24429589-D711-11D2-9F41-00C04F6BC6A5}";
                        pObjCls         = new AnnotationFeatureClassDescriptionClass();
                        break;

                    case (esriFeatureType.esriFTDimension):
                        uidCLSEXT       = new UIDClass();
                        uidCLSEXT.Value = "{48F935E2-DA66-11D3-80CE-00C04F601565}";
                        break;
                    }
                }
                //IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace;
                IFieldChecker fdCheker = new FieldCheckerClass();//yjl20110804 add
                pEnumFieldError            = null;
                pFixedField                = null;
                fdCheker.ValidateWorkspace = pWks as IWorkspace;
                fdCheker.Validate(pFeaCls.Fields, out pEnumFieldError, out pFixedField);

                //string strShapeFieldName = pfeaturelayer.FeatureClass.ShapeFieldName;//geometry字段名
                //string[] strShapeNames = strShapeFieldName.Split('.');
                //strShapeFieldName = strShapeNames[strShapeNames.GetLength(0) - 1];

                IFields pFields = new FieldsClass();
                if (pObjCls != null)
                {
                    IFeatureClassDescription pClsDes = pObjCls as IFeatureClassDescription;
                    pFields = pObjCls.RequiredFields;
                }

                IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;

                for (int i = 0; i < pFeaCls.Fields.FieldCount; i++)
                {
                    IField   pf            = pFeaCls.Fields.get_Field(i);
                    string   strFieldName  = pf.Name;
                    string[] strFieldNames = strFieldName.Split('.');

                    bool blnfind = false;
                    for (int j = 0; j < pFields.FieldCount; j++)
                    {
                        IField   pf2        = pFields.get_Field(j);
                        string[] strfields2 = pf2.Name.Split('.');
                        if (strfields2[strfields2.GetLength(0) - 1].ToUpper() == strFieldNames[strFieldNames.GetLength(0) - 1].ToUpper())
                        {
                            blnfind = true;
                            break;
                        }
                    }

                    if (blnfind)
                    {
                        continue;
                    }

                    if (pFeaCls.FeatureType == esriFeatureType.esriFTAnnotation)
                    {
                        if (pFeaCls.ShapeFieldName == pf.Name)
                        {
                            continue;
                        }
                    }

                    if (pFeaCls.LengthField != null)
                    {
                        if (pFeaCls.LengthField.Name == pf.Name)
                        {
                            continue;
                        }
                    }
                    if (pFeaCls.AreaField != null)
                    {
                        if (pFeaCls.AreaField.Name == pf.Name)
                        {
                            continue;
                        }
                    }

                    IClone     pClone         = pFeaCls.Fields.get_Field(i) as IClone;
                    IField     pTempField     = pClone.Clone() as IField;
                    IFieldEdit pTempFieldEdit = pTempField as IFieldEdit;

                    if (pFieldsEdit.FindField(strFieldNames[strFieldNames.GetLength(0) - 1]) > -1)
                    {
                        continue;
                    }

                    pTempFieldEdit.Name_2 = strFieldNames[strFieldNames.GetLength(0) - 1];
                    pFieldsEdit.AddField(pTempField);
                }

                string   strShapeFieldName = pFeaCls.ShapeFieldName;
                string[] strShapeNames     = strShapeFieldName.Split('.');
                strShapeFieldName = strShapeNames[strShapeNames.GetLength(0) - 1];

                //修改geometrydef
                IField pFieldShape = pFeaCls.Fields.get_Field(pFeaCls.Fields.FindField(pFeaCls.ShapeFieldName));

                if (pFieldShape != null)
                {
                    IFieldEdit pFieldShapeEdit = pFields.get_Field(pFields.FindField(strShapeFieldName)) as IFieldEdit;
                    pFieldShapeEdit.GeometryDef_2 = pFieldShape.GeometryDef;
                }

                IGeometryDef pGeoDef  = pFieldShape.GeometryDef;
                double       dblIndex = pGeoDef.get_GridSize(0);

                //添加两个字段一个时间 一个名称
                if (pFields.FindField("ImportTime") < 0)
                {
                    IField     pNewField1 = new FieldClass();
                    IFieldEdit pNewEdit1  = pNewField1 as IFieldEdit;
                    pNewEdit1.Name_2      = "ImportTime";
                    pNewEdit1.AliasName_2 = "入库时间";
                    pNewEdit1.Type_2      = esriFieldType.esriFieldTypeDate;
                    pFieldsEdit.AddField(pNewField1);
                }

                if (pFields.FindField("ImportUser") < 0)
                {
                    IField     pNewField2 = new FieldClass();
                    IFieldEdit pNewEdit2  = pNewField2 as IFieldEdit;
                    pNewEdit2.Name_2      = "ImportUser";
                    pNewEdit2.AliasName_2 = "入库人";
                    pNewEdit2.Type_2      = esriFieldType.esriFieldTypeString;
                    pFieldsEdit.AddField(pNewField2);
                }

                IFeatureClass targetFeatureclass = null;


                if (pFeaCls.FeatureType == esriFeatureType.esriFTAnnotation)
                {
                    IAnnoClass pAnno = pFeaCls.Extension as IAnnoClass;

                    IFeatureWorkspaceAnno pWksAnno = pWks as IFeatureWorkspaceAnno;
                    IGraphicsLayerScale   pGl      = new GraphicsLayerScaleClass();
                    pGl.ReferenceScale = pAnno.ReferenceScale;
                    pGl.Units          = pAnno.ReferenceScaleUnits;
                    targetFeatureclass = pWksAnno.CreateAnnotationClass(name, pFields, pFeaCls.CLSID, pFeaCls.EXTCLSID, strShapeFieldName, "", pFeaDataset, null, pAnno.AnnoProperties, pGl, pAnno.SymbolCollection, false);
                }
                else
                {
                    if (pFeaDataset != null)
                    {
                        targetFeatureclass = pFeaDataset.CreateFeatureClass(name, pFixedField, uidCLSID, uidCLSEXT, pFeaCls.FeatureType, strShapeFieldName, "");
                    }
                    else
                    {
                        targetFeatureclass = pWks.CreateFeatureClass(name, pFixedField, uidCLSID, uidCLSEXT, pFeaCls.FeatureType, strShapeFieldName, "");
                    }
                }

                return(targetFeatureclass);
            }
            catch (Exception ex)
            {
                if (ex.Message == "Cannot create a low precision dataset in a high precision database.")
                {
                    MessageBox.Show("数据必须是ArcGis9.2的数据,请将数据处理成ArcGis9.2的数据!");
                }
            }
            IFeatureClass featureclass = null;

            return(featureclass);
        }
示例#57
0
        /// <summary>
        /// 复制源图层到目标dataset中的目标图层
        /// </summary>
        /// <param name="sourceWorkspaceDataset">源图层集</param>
        /// <param name="targetWorkspaceDataset">目标图层集</param>
        /// <param name="sourceFeatureClass">源图层</param>
        /// <param name="nameOfTargetFeatureClass">待创建的图层名</param>
        public static IFeatureClass ConvertFeatureClass(IDataset sourceWorkspaceDataset, IDataset targetWorkspaceDataset,
                                                        IFeatureClass sourceFeatureClass,
                                                        string nameOfTargetFeatureClass)
        {
            IFeatureClass TragetFeatureClass = null;

            try
            {
                IFeatureClassName nameOfSourceFeatureClass =
                    ((IDataset)sourceFeatureClass).FullName as IFeatureClassName;

                IDatasetName pSourceDsName = (IDatasetName)sourceWorkspaceDataset.FullName;
                IDatasetName pTargetDsName = (IDatasetName)targetWorkspaceDataset.FullName;

                IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
                targetFeatureClassName.FeatureDatasetName = pTargetDsName;
                IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName;
                targetDatasetName.Name = nameOfTargetFeatureClass;


                //Validate the field names because you are converting between different workspace types.
                IFieldChecker   fieldChecker = new FieldCheckerClass();
                IFields         targetFeatureClassFields;
                IFields         sourceFeatureClassFields = sourceFeatureClass.Fields;
                IEnumFieldError enumFieldError;
                // Most importantly set the input and validate workspaces!

                fieldChecker.InputWorkspace    = sourceWorkspaceDataset.Workspace;
                fieldChecker.ValidateWorkspace = targetWorkspaceDataset.Workspace;
                fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);
                // Loop through the output fields to find the geomerty field
                IField geometryField;
                for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
                {
                    if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        geometryField = targetFeatureClassFields.get_Field(i);
                        // Get the geometry field's geometry defenition
                        IGeometryDef geometryDef = geometryField.GeometryDef;
                        //Give the geometry definition a spatial index grid count and grid size
                        IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef;
                        //targetFCGeoDefEdit.GridCount_2 = 1;
                        //targetFCGeoDefEdit.set_GridSize(0, 0);
                        //Allow ArcGIS to determine a valid grid size for the data loaded
                        targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;
                        // we want to convert all of the features
                        IQueryFilter queryFilter = new QueryFilterClass();
                        queryFilter.WhereClause = "";
                        // Load the feature class
                        IFeatureDataConverter fctofc = new FeatureDataConverterClass();

                        IEnumInvalidObject enumErrors =
                            fctofc.ConvertFeatureClass(nameOfSourceFeatureClass, queryFilter,
                                                       pTargetDsName as IFeatureDatasetName, targetFeatureClassName,
                                                       geometryDef, targetFeatureClassFields, "", 1000, 0);
                        break;
                    }
                }

                string strTargetFtCls = ((IDatasetName)targetFeatureClassName).Name;
                TragetFeatureClass =
                    ((IFeatureWorkspace)targetWorkspaceDataset.Workspace).OpenFeatureClass(strTargetFtCls);
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                return(null);
            }
            return(TragetFeatureClass);
        }
示例#58
0
        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;
        }
示例#59
0
        private static IFeatureClass OpenOrCreateShapeFile(string a_ShapeFilePath, bool a_CreateIfNotExists)
        {
            var a_WorkspaceFactory        = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace a_Workspace = null;

            try
            {
                var a_Directory = Path.GetDirectoryName(a_ShapeFilePath);
                if (string.IsNullOrEmpty(a_Directory))
                {
                    throw new Exception("Directory name is empty");
                }
                if (!Directory.Exists(a_Directory))
                {
                    Directory.CreateDirectory(a_Directory);
                }
                var a_TableName = Path.GetFileNameWithoutExtension(a_ShapeFilePath);
                if (string.IsNullOrEmpty(a_TableName))
                {
                    throw new Exception("Table name is empty");
                }
                a_Workspace =
                    (IFeatureWorkspace)a_WorkspaceFactory.OpenFromString(string.Format("Database={0}", a_Directory), 0);
                IFeatureClass a_FeatureClass = null;
                if (((IWorkspace2)a_Workspace).NameExists[esriDatasetType.esriDTFeatureClass, a_TableName])
                {
                    a_FeatureClass = a_Workspace.OpenFeatureClass(a_TableName);
                }
                else if (a_CreateIfNotExists)
                {
                    IFeatureClassDescription a_FeatureClassDescription = new FeatureClassDescriptionClass();
                    var a_ObjectClassDescription = (IObjectClassDescription)a_FeatureClassDescription;
                    var a_Fields     = a_ObjectClassDescription.RequiredFields;
                    var a_FieldsEdit = (IFieldsEdit)a_Fields;

                    // Find the shape field in the required fields and modify its GeometryDef to
                    // use point geometry and to set the spatial reference.
                    var a_ShapeFieldIndex = a_Fields.FindField(a_FeatureClassDescription.ShapeFieldName);
                    var a_Field           = a_Fields.Field[a_ShapeFieldIndex];
                    var a_GeometryDef     = a_Field.GeometryDef;
                    var a_GeometryDefEdit = (IGeometryDefEdit)a_GeometryDef;
                    a_GeometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;

                    #region fields

                    a_Field = new FieldClass
                    {
                        IFieldEdit_Name_2         = fnCountryName,
                        IFieldEdit_Type_2         = esriFieldType.esriFieldTypeString,
                        IFieldEdit_Length_2       = 255,
                        IFieldEdit_DefaultValue_2 = string.Empty,
                        IFieldEdit_Editable_2     = true,
                    };
                    a_FieldsEdit.AddField(a_Field);

                    var a_AddIntField = new Action <string>(a_FieldName =>
                    {
                        a_Field = new FieldClass
                        {
                            IFieldEdit_Name_2         = a_FieldName,
                            IFieldEdit_Type_2         = esriFieldType.esriFieldTypeInteger,
                            IFieldEdit_DefaultValue_2 = 0,
                            IFieldEdit_Editable_2     = true,
                        };
                        a_FieldsEdit.AddField(a_Field);
                    });

                    a_AddIntField(fnWide);
                    a_AddIntField(fnLocal);
                    a_AddIntField(fnRegional);
                    a_AddIntField(fnLow);
                    a_AddIntField(fnHigh);
                    a_AddIntField(fnHighAndVeryHigh);
                    a_AddIntField(fnMedium);
                    a_AddIntField(fnBasic);
                    a_AddIntField(fnClass1);
                    a_AddIntField(fnClass2);
                    a_AddIntField(fnClass3);
                    a_AddIntField(fnClass4);
                    a_AddIntField(fnScore);
                    a_AddIntField(fnExtinctInWild);
                    a_AddIntField(fnCriticallyEndangered);
                    a_AddIntField(fnEndangered);
                    a_AddIntField(fnVulnerable);
                    a_AddIntField(fnNearThreatened);
                    a_AddIntField(fnLeastConcern);
                    a_AddIntField(fnDataDeficient);
                    a_AddIntField(fnNotEvaluated);

                    #endregion fields

                    IFieldChecker   a_FieldChecker    = new FieldCheckerClass();
                    IEnumFieldError a_EnumFieldError  = null;
                    IFields         a_ValidatedFields = null;
                    a_FieldChecker.ValidateWorkspace = (IWorkspace)a_Workspace;
                    a_FieldChecker.Validate(a_Fields, out a_EnumFieldError, out a_ValidatedFields);

                    a_FeatureClass = a_Workspace.CreateFeatureClass(
                        a_TableName,
                        a_ValidatedFields,
                        a_ObjectClassDescription.InstanceCLSID,
                        a_ObjectClassDescription.ClassExtensionCLSID,
                        esriFeatureType.esriFTSimple,
                        ((IFeatureClassDescription)a_ObjectClassDescription).ShapeFieldName,
                        string.Empty);
                }
                return(a_FeatureClass);
            }
            finally
            {
                if (a_Workspace != null)
                {
                    Marshal.ReleaseComObject(a_Workspace);
                }
                Marshal.ReleaseComObject(a_WorkspaceFactory);
            }
        }
示例#60
0
        public void CopyFeatures(LoadTarget target)
        {
            IWorkspaceFactory sourceWsf;

            if (System.IO.Path.GetExtension(target.In_Directory).ToUpper().Equals(".GDB"))
            {
                sourceWsf = new FileGDBWorkspaceFactoryClass();
            }
            else
            {
                sourceWsf = new ShapefileWorkspaceFactoryClass();
            }
            IFeatureWorkspace sourceFeatWs       = sourceWsf.OpenFromFile(target.In_Directory, 0) as IFeatureWorkspace;
            IFeatureClass     sourceFeatureClass = sourceFeatWs.OpenFeatureClass(target.In_FileName);

            IWorkspaceFactory targetWsf;

            if (System.IO.Path.GetExtension(target.Out_Directory).ToUpper().Equals(".GDB"))
            {
                targetWsf = new FileGDBWorkspaceFactoryClass();
            }
            else
            {
                targetWsf = new ShapefileWorkspaceFactoryClass();
            }

            IWorkspace targetWs = targetWsf.OpenFromFile(target.Out_Directory, 0) as IWorkspace;

            string targetFileName;

            if (System.IO.Path.GetExtension(target.Out_Directory).ToUpper().Equals(".GDB"))
            {
                targetFileName = LoadHelper.GetNameGDB(target.Out_Directory, target.Out_FileName);
            }
            else
            {
                targetFileName = LoadHelper.GetNameShapeFile(target.Out_Directory, target.Out_FileName);
            }

            IFeatureWorkspace        targetFeatWs            = targetWs as IFeatureWorkspace;
            IFeatureClassDescription featureClassDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription  objectClassDescription  = featureClassDescription as IObjectClassDescription;

            IFields         pFields         = sourceFeatureClass.Fields;
            IFieldChecker   pFieldChecker   = new FieldCheckerClass();
            IEnumFieldError pEnumFieldError = null;
            IFields         vFields         = null;

            pFieldChecker.ValidateWorkspace = targetWs as IWorkspace;
            pFieldChecker.Validate(pFields, out pEnumFieldError, out vFields);

            IFeatureClass sdeFeatureClass = null;

            if (sdeFeatureClass == null)
            {
                sdeFeatureClass = targetFeatWs.CreateFeatureClass(targetFileName, vFields,
                                                                  objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID,
                                                                  sourceFeatureClass.FeatureType, sourceFeatureClass.ShapeFieldName, "");
                IFeatureCursor featureCursor    = sourceFeatureClass.Search(null, true);
                IFeature       feature          = featureCursor.NextFeature();
                IFeatureCursor sdeFeatureCursor = sdeFeatureClass.Insert(true);
                IFeatureBuffer sdeFeatureBuffer;
                IQueryFilter   qf = new QueryFilterClass();
                target.Size = sourceFeatureClass.FeatureCount(qf);
                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.ToLower().Contains("area") || shpField.Name.ToLower().Contains("leng") || shpField.Name.ToLower().Contains("fid") || shpField.Name.ToLower().Contains("objectid"))
                        {
                            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();
                    target.Progress++;
                }
                featureCursor.Flush();
                target.IsFinished = true;
                target.IsBusy     = false;
            }
        }