예제 #1
0
        /// <param name="pFeatureClass">融合要素</param>
        /// <param name="dissField">融合字段</param>
        private IFeatureClass Dissolve(IFeatureClass pFeatureClass, string dissField)
        {
            IFeatureClass pOutFeatureClass = null;

            try
            {
                if (this.gp == null)
                {
                    this.gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
                }

                ESRI.ArcGIS.DataManagementTools.Dissolve pDissolve = new ESRI.ArcGIS.DataManagementTools.Dissolve();
                this.gp.OverwriteOutput     = true;
                pDissolve.in_features       = pFeatureClass;
                pDissolve.dissolve_field    = dissField;
                pDissolve.out_feature_class = System.Environment.CurrentDirectory + @"\temp\Dissolve.shp";
                pDissolve.multi_part        = "true"; //跨区域融合;
                IGeoProcessorResult result = (IGeoProcessorResult)gp.Execute(pDissolve, null);

                if (result.Status != ESRI.ArcGIS.esriSystem.esriJobStatus.esriJobSucceeded)
                {
                    return(null);
                }
                else
                {
                    pOutFeatureClass = this.gp.Open(result.ReturnValue) as IFeatureClass;
                }
            }
            catch (System.Exception ex)
            {
                return(null);
            }
            return(pOutFeatureClass);
        }
        private static void RunGPFieldMapping()
        {
            // Initialize the Geoprocessor
            ESRI.ArcGIS.Geoprocessor.Geoprocessor GP = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            GP.OverwriteOutput = true;

            // Create the GPUtilites object
            IGPUtilities gputilities = new GPUtilitiesClass();

            // Create a DETable data element object 
            IDETable inputTableA = (IDETable)gputilities.MakeDataElement(@"C:\data\citiblocks.gdb\census", null, null);

            // Create an array of input tables
            IArray inputtables = new ArrayClass();
            inputtables.Add(inputTableA);

            // Initialize the GPFieldMapping
            IGPFieldMapping fieldmapping = new GPFieldMappingClass();
            fieldmapping.Initialize(inputtables, null);

            // Create a new output field
            IFieldEdit trackidfield = new FieldClass();
            trackidfield.Name_2 = "TRACTID";
            trackidfield.Type_2 = esriFieldType.esriFieldTypeString;
            trackidfield.Length_2 = 50;

            // Create a new FieldMap
            IGPFieldMap trackid = new GPFieldMapClass();
            trackid.OutputField = trackidfield;

            // Find field map "STFID" containing the input field "STFID". Add input field to the new field map.
            int fieldmap_index = fieldmapping.FindFieldMap("STFID");
            IGPFieldMap stfid_fieldmap = fieldmapping.GetFieldMap(fieldmap_index);
            int field_index = stfid_fieldmap.FindInputField(inputTableA, "STFID");
            IField inputField = stfid_fieldmap.GetField(field_index);
            trackid.AddInputField(inputTableA, inputField, 5, 10);

            // Add the new field map to the field mapping
            fieldmapping.AddFieldMap(trackid);

            // Execute Table to Table tool using the FieldMapping
            TableToTable tblTotbl = new TableToTable();
            tblTotbl.in_rows = inputTableA;
            tblTotbl.out_path = @"C:\data\citiblocks.gdb";
            tblTotbl.out_name = "census_out";
            tblTotbl.field_mapping = fieldmapping;

            object sev = null;
            try
            {
                GP.Execute(tblTotbl, null);
                System.Windows.Forms.MessageBox.Show(GP.GetMessages(ref sev));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                System.Windows.Forms.MessageBox.Show(GP.GetMessages(ref sev));
            }
        }
예제 #3
0
파일: BaseClass.cs 프로젝트: secondii/Yutai
 private static void ReturnMessages(ESRI.ArcGIS.Geoprocessor.Geoprocessor gp)
 {
     if (gp.MessageCount > 0)
     {
         for (int i = 0; i <= (gp.MessageCount - 1); i++)
         {
             Console.WriteLine(gp.GetMessage(i));
         }
     }
 }
예제 #4
0
        public bool Excute()
        {
            bool flag = false;

            this.m_sb.Remove(0, this.m_sb.Length);
            ESRI.ArcGIS.Geoprocessor.Geoprocessor geoprocessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            geoprocessor.RegisterGeoProcessorEvents(this);
            try
            {
                geoprocessor.OverwriteOutput = true;
                geoprocessor.ClearMessages();
                try
                {
                    object obj2 = geoprocessor.Execute(this.m_pGPProcess, null);
                    flag = true;
                }
                catch (Exception)
                {
                    flag = false;
                }
            }
            catch
            {
            }
            geoprocessor.UnRegisterGeoProcessorEvents(this);
            if (!this.m_IsPostToolExecute)
            {
                if (geoprocessor.MessageCount > 0)
                {
                    for (int i = 0; i <= (geoprocessor.MessageCount - 1); i++)
                    {
                        if (this.m_sb.Length > 0)
                        {
                            this.m_sb.Append("\r\n");
                        }
                        this.m_sb.Append(geoprocessor.GetMessage(i));
                    }
                }
                this.txtMessage.Text = this.m_sb.ToString();
            }
            this.xpProgressBar1.Position = this.xpProgressBar1.PositionMax;
            this.timer1.Enabled          = false;
            this.m_IsPostToolExecute     = false;
            this.m_IsPreExecute          = false;
            if (this.chkAutoCompleteSucc.Checked)
            {
                base.Close();
                if (this.m_attchForm != null)
                {
                    this.m_attchForm.Close();
                }
            }
            return(flag);
        }
예제 #5
0
        private void btnBuffer_Click(object sender, EventArgs e)
        {
            //缓冲距离
            double bufferDistance;

            //输入的缓冲距离转换为double
            double.TryParse(txtBufferDistance.Text.ToString(), out bufferDistance);

            //判断输出路径是否合法
            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(txtOutputPath.Text)) ||
                ".shp" != System.IO.Path.GetExtension(txtOutputPath.Text))
            {
                MessageBox.Show("输出路径错误!");
                return;
            }

            //判断图层个数
            if (mHookHelper.FocusMap.LayerCount == 0)
            {
                return;
            }
            //获取图层
            IFeatureLayer pFeatureLayer = GetFeatureLayer((string)cboLayers.SelectedItem);

            if (null == pFeatureLayer)
            {
                MessageBox.Show("图层 " + (string)cboLayers.SelectedItem + "不存在!\r\n");
                return;
            }

            //获取一个geoprocessor的实例
            ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            //OverwriteOutput为真时,输出图层会覆盖当前文件夹下的同名图层
            gp.OverwriteOutput = true;
            //缓冲区保存路径
            strOutputPath = txtOutputPath.Text;
            //创建一个Buffer工具的实例
            ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(pFeatureLayer, strOutputPath, bufferDistance.ToString());
            //执行缓冲区分析
            IGeoProcessorResult results = null;

            results = (IGeoProcessorResult)gp.Execute(buffer, null);
            //判断缓冲区是否成功生成
            if (results.Status != esriJobStatus.esriJobSucceeded)
            {
                MessageBox.Show("图层" + pFeatureLayer.Name + "缓冲区生成失败!");
            }
            else
            {
                this.DialogResult = DialogResult.OK;
                MessageBox.Show("缓冲区生成成功!");
            }
        }
예제 #6
0
        /// <summary>
        /// 两面相交
        /// </summary>
        private void intersect()
        {
            //两面相交
            ESRI.ArcGIS.Geoprocessor.Geoprocessor GP        = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            ESRI.ArcGIS.AnalysisTools.Intersect   intersect = new ESRI.ArcGIS.AnalysisTools.Intersect();

            intersect.in_features       = @"C:\Users\航\Desktop\同济新村shp数据\同济新村房屋.shp;C:\Users\航\Desktop\同济新村shp数据\生成地块.shp";
            intersect.out_feature_class = @"C:\Users\航\Desktop\同济新村shp数据\intersect.shp";

            IGPProcess GProcess1 = intersect;

            GP.Execute(GProcess1, null);

            //如果显示
            //Form1.mainForm.axMapControl1.AddShapeFile(@"C:\Users\航\Desktop\同济新村shp数据\", "intersect.shp");
            //Form1.mainForm.axMapControl1.Refresh();
        }
예제 #7
0
        private void btnIntersect_Click(object sender, EventArgs e)
        {//添加两个以上图层时才允许叠置
            if (this.axMapControl1.LayerCount < 2)
            {
                return;
            }
            ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            //OverwriteOutput为真时,输出图层会覆盖当前文件夹下的同名图层
            gp.OverwriteOutput = true;
            //创建重置分析实例
            Intersect intersectTool = new Intersect();
            //获取mapcontrol中的前两个图层
            ILayer plnputLayer1 = this.axMapControl1.get_Layer(0);
            ILayer plnputLayer2 = this.axMapControl1.get_Layer(1);
            //转换为object类型
            object inputfeature1 = plnputLayer1;
            object inputfeature2 = plnputLayer2;
            //设置叠置分析的多个对象
            IGpValueTableObject pObject = new GpValueTableObjectClass();

            pObject.SetColumns(2);
            pObject.AddRow(ref inputfeature1);
            pObject.AddRow(ref inputfeature2);
            intersectTool.in_features = pObject;
            //设置输出路径
            string strTempPath   = @"D:\Temp";
            string strOutputPath = strTempPath + plnputLayer1.Name + "_" + plnputLayer2.Name + "_Intersect.shp";

            intersectTool.out_feature_class = strOutputPath;
            //执行叠置分析
            IGeoProcessorResult result = null;

            result = gp.Execute(intersectTool, null) as IGeoProcessorResult;
            //判断叠置分析是否成功
            if (result.Status != ESRI.ArcGIS.esriSystem.esriJobStatus.esriJobSucceeded)
            {
                MessageBox.Show("叠置求交失败!!");
            }
            else
            {
                MessageBox.Show("叠置求交成功!!");
                int index = strOutputPath.LastIndexOf("\\");
                this.axMapControl1.AddShapeFile(strOutputPath.Substring(0, index), strOutputPath.Substring(index));
            }
        }
예제 #8
0
        //Creates raster catalog using GP CreateRasterCatalog class
        static void CreateRasterCatalog_GP(object rasterCoordSys, object geometryCoordsys)
        {
            //Initialize GeoProcessor
            ESRI.ArcGIS.Geoprocessor.Geoprocessor geoProcessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();

            //CreateRasterCatalog GP tool
            CreateRasterCatalog createRasterCatalog = new CreateRasterCatalog();

            //Set parameters
            createRasterCatalog.out_path = sdePath;
            createRasterCatalog.out_name = catalogName;
            createRasterCatalog.raster_spatial_reference = rasterCoordSys;
            createRasterCatalog.spatial_reference        = geometryCoordsys;

            //Execute the tool to create a raster catalog
            geoProcessor.Execute(createRasterCatalog, null);
            ReturnMessages(geoProcessor);
        }
예제 #9
0
        static void LoadDirToRasterCatalog(string outRasterCatalog, string inputDir)
        {
            //Initialize GeoProcessor
            ESRI.ArcGIS.Geoprocessor.Geoprocessor geoProcessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();

            //Set parameters
            IVariantArray parameters = new VarArrayClass();

            //Set input folder
            parameters.Add(inputDir);

            //Set target GDB raster catalog
            parameters.Add(outRasterCatalog);

            //Execute the tool to load rasters in the directory to raster catalog
            geoProcessor.Execute("WorkspaceToRasterCatalog", parameters, null);
            ReturnMessages(geoProcessor);
        }
예제 #10
0
파일: BaseClass.cs 프로젝트: secondii/Yutai
 public static bool RunTool(ESRI.ArcGIS.Geoprocessor.Geoprocessor geoprocessor, IGPProcess process,
                            ITrackCancel TC)
 {
     geoprocessor.OverwriteOutput = true;
     geoprocessor.ClearMessages();
     try
     {
         object obj2 = geoprocessor.Execute(process, TC);
         ReturnMessages(geoprocessor);
         return(true);
     }
     catch (Exception exception)
     {
         MessageBox.Show(exception.Message);
         ReturnMessages(geoprocessor);
         return(false);
     }
 }
예제 #11
0
        public static void ExportLayerToShapefile(string shapePath, string shapeName, ILayer source)
        {
            try
            {
                // cast the selected/requested layer into a feature layer
                ESRI.ArcGIS.Carto.IFeatureLayer featureLayer = (IFeatureLayer)source;

                // create a new feature class to feature class converter utility
                ESRI.ArcGIS.ConversionTools.FeatureClassToFeatureClass fc2fc
                    = new ESRI.ArcGIS.ConversionTools.FeatureClassToFeatureClass();

                // set the input feature layer
                fc2fc.in_features = featureLayer;

                // set the output path and Shapefile name
                fc2fc.out_path = shapePath;
                fc2fc.out_name = shapeName + ".shp";

                // create a new GeoProcessor
                ESRI.ArcGIS.Geoprocessor.Geoprocessor geoprocessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
                geoprocessor.TemporaryMapLayers = true;

                // execute the FeatureClassToFeatureClass
                geoprocessor.Execute(fc2fc, null);

                // export a copy of the layer file definition too for upload/style at a later time
                ESRI.ArcGIS.DataManagementTools.SaveToLayerFile saveToLayerFile
                    = new ESRI.ArcGIS.DataManagementTools.SaveToLayerFile();
                saveToLayerFile.in_layer  = source;
                saveToLayerFile.out_layer = shapePath + "\\" + shapeName + ".lyr";

                // execute the FeatureClassToFeatureClass
                geoprocessor.Execute(saveToLayerFile, null);

                // remove reference to the tool and geoprocessor
                fc2fc        = null;
                geoprocessor = null;
            }
            catch (Exception ex)
            {
                // an error occured
                System.Windows.Forms.MessageBox.Show("Error: " + ex.Message);
            }
        }
예제 #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            //判断Mapcontrol中是否包含图层
            if (this.axMapControl1.LayerCount == 0)
            {
                return;
            }
            //获取mapcontrol最终的第一图层
            ILayer pLayer = this.axMapControl1.Map.get_Layer(0);
            //输出路径,可以自行制定
            string strOutputPath = @"D:\Buffer.shp";
            //缓冲半径
            double dbDistace = 1.0;

            //获取一个geoprocessor的实例,避免与命名空间Geoprocessing中的Geoprocessor发生引用错误
            ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            //OverwriteOutput为真时,输出图层会覆盖当前文件夹下的同名图层
            gp.OverwriteOutput = true;
            //创建应Buffer工具的实例
            ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(pLayer, strOutputPath, dbDistace);

            //执行缓冲区分析
            IGeoProcessorResult result = null;

            result = gp.Execute(buffer, null) as IGeoProcessorResult;
            //判断缓冲区分析是否成功
            if (result.Status != esriJobStatus.esriJobSucceeded)
            {
                MessageBox.Show("图层" + pLayer.Name + "缓冲区生成失败!");
            }
            else
            {
                MessageBox.Show("缓冲区生成成功!");
                //将生成成功的图层加入到Mapcontrol中
                int index = strOutputPath.LastIndexOf("\\");
                this.axMapControl1.AddShapeFile(strOutputPath.Substring(0, index), strOutputPath.Substring(index));
            }
        }
예제 #13
0
        public bool Excute()
        {
            bool isPostToolExecute = false;

            this.m_sb.Remove(0, this.m_sb.Length);
            ESRI.ArcGIS.Geoprocessor.Geoprocessor geoprocessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            geoprocessor.RegisterGeoProcessorEvents(this);
            BaseClass.RunTool(geoprocessor, this.m_pGPProcess, null);
            geoprocessor.UnRegisterGeoProcessorEvents(this);
            isPostToolExecute = this.m_IsPostToolExecute;
            if (!this.m_IsPostToolExecute)
            {
                if (geoprocessor.MessageCount > 0)
                {
                    for (int i = 0; i <= (geoprocessor.MessageCount - 1); i++)
                    {
                        if (this.m_sb.Length > 0)
                        {
                            this.m_sb.Append("\r\n");
                        }
                        this.m_sb.Append(geoprocessor.GetMessage(i));
                    }
                }
                else
                {
                    this.m_sb.Append("命令执行失败!");
                }
                this.txtMessage.Text = this.m_sb.ToString();
            }
            this.timer1.Enabled      = false;
            this.m_IsPostToolExecute = false;
            this.m_IsPreExecute      = false;
            ComReleaser.ReleaseCOMObject(geoprocessor);
            ComReleaser.ReleaseCOMObject(this.m_pGPProcess);
            geoprocessor = null;
            return(isPostToolExecute);
        }
        static void LoadDirToRasterCatalog(string outRasterCatalog, string inputDir)
        {
            //Initialize GeoProcessor
            ESRI.ArcGIS.Geoprocessor.Geoprocessor geoProcessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();

            //Set parameters
            IVariantArray parameters = new VarArrayClass();

            //Set input folder
            parameters.Add(inputDir);

            //Set target GDB raster catalog
            parameters.Add(outRasterCatalog);

            //Execute the tool to load rasters in the directory to raster catalog
            geoProcessor.Execute("WorkspaceToRasterCatalog", parameters, null);
            ReturnMessages(geoProcessor);
        }
예제 #15
0
        /// <summary>
        /// Sends the selected options to the Filtering python script as XML.
        /// </summary>
        /// <param name="sSuffix"></param>
        /// <returns></returns>
        public IFeatureLayer FilterLayer(string sSuffix)
        {
            IFeatureLayer pResult    = null;
            string        sWorkspace = m_sWorkspace;
            string        sInputFC   = m_sLayername;

            try
            {
                if (m_bFilterDistance)
                {
                    XmlDocument oDoc      = new XmlDocument();
                    XmlElement  oRootNode = oDoc.CreateElement("Settings");

                    //*************************************************************/
                    //Input/Output feature classes
                    //Base stations table
                    XmlElement oNode = oDoc.CreateElement("InputFC");
                    oNode.InnerText = sWorkspace + "\\" + sInputFC;
                    oRootNode.AppendChild(oNode);

                    oNode           = oDoc.CreateElement("OutputCleanedFeature");
                    oNode.InnerText = sWorkspace + "\\" + sInputFC + "_" + sSuffix;
                    oRootNode.AppendChild(oNode);

                    oNode           = oDoc.CreateElement("OutputDeletedFeature");
                    oNode.InnerText = sWorkspace + "\\" + sInputFC + "_" + sSuffix + "_Deleted";
                    oRootNode.AppendChild(oNode);

                    oNode           = oDoc.CreateElement("FilterDistance");
                    oNode.InnerText = (m_bFilterDistance ? "T" : "F");
                    oRootNode.AppendChild(oNode);

                    oNode           = oDoc.CreateElement("MaximumDistance");
                    oNode.InnerText = m_dMaximumDistance.ToString();
                    oRootNode.AppendChild(oNode);

                    oDoc.AppendChild(oRootNode);

                    clsPython pPython = new clsPython();
                    pPython.RunPythonScript("filter_fortrackgen.py", oDoc, "FilterSettings.xml");
                }
                else if (m_bSmoothLines)
                {
                    IMxDocument   pMxDoc = ArcMap.Document;
                    IFeatureLayer pFL    = clsStatic.GetLayerFromMap(sWorkspace, sInputFC);
                    if (pFL != null)
                    {
                        pMxDoc.DelayUpdateContents = true;
                        pMxDoc.FocusMap.DeleteLayer((ILayer)pFL);
                    }

                    ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
                    gp.OverwriteOutput = true;
                    gp.AddOutputsToMap = false;

                    ESRI.ArcGIS.CartographyTools.SmoothLine smoothLine = new ESRI.ArcGIS.CartographyTools.SmoothLine();
                    smoothLine.in_features       = sWorkspace + "\\" + sInputFC;
                    smoothLine.out_feature_class = sWorkspace + "\\" + sInputFC + "_" + sSuffix;
                    smoothLine.algorithm         = m_sAlgorithm;
                    if (m_sAlgorithm == "PAEK")
                    {
                        smoothLine.tolerance       = m_iTolerance;
                        smoothLine.endpoint_option = m_sEndpointOption;
                    }
                    else
                    {
                        smoothLine.tolerance = 0;
                    }

                    smoothLine.error_option = m_sErrorOption;
                    gp.Execute(smoothLine, null);
                    ProcessGPMessages(gp);

                    pMxDoc.FocusMap.AddLayer((ILayer)pFL);
                }
            }
            catch (COMException exCom)
            {
                MessageBox.Show("You need an ArcInfo license to access this operation.", clsStatic.g_cProjectName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                clsStatic.ShowErrorMessage(ex.ToString());
            }
            finally
            {
                pResult = clsStatic.GetFeatureLayer(sWorkspace, sInputFC + "_" + sSuffix);
            }
            return(pResult);
        }
        //开始分析
        private void btnOK_Click(object sender, EventArgs e)
        {
            //判断是否选择要素
            if (this.txtInputLayer.Text == "" || this.txtInputLayer.Text == null ||
                this.txtOverlayLayer.Text == "" || this.txtOverlayLayer.Text == null)
            {
                txtMessage.Text = "请选择参加叠置分析的图层!";
                return;
            }
            ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            //OverwriteOutput为真时,输出图层会覆盖当前文件夹下的同名图层
            gp.OverwriteOutput = true;

            //设置参与叠置分析的多个对象
            object inputFeat            = this.txtInputLayer.Text;
            object overlayFeat          = this.txtOverlayLayer.Text;
            IGpValueTableObject pObject = new GpValueTableObjectClass();

            pObject.SetColumns(2);
            pObject.AddRow(ref inputFeat);
            pObject.AddRow(ref overlayFeat);

            //获取要素名称
            string str     = System.IO.Path.GetFileName(this.txtInputLayer.Text);
            int    index   = str.LastIndexOf(".");
            string strName = str.Remove(index);

            //设置输出路径
            strOutputPath = txtOutputLayerPath.Text;

            //叠置分析结果
            IGeoProcessorResult result = null;

            //创建叠置分析实例,执行叠置分析
            string strOverlay = cmbOverlayType.SelectedItem.ToString();

            try
            {
                //添加处理过程消息
                txtMessage.Text = "开始叠置分析……" + "\r\n";
                switch (strOverlay)
                {
                case "叠置求交(Intersect)":
                    Intersect intersectTool = new Intersect();
                    //设置输入要素
                    intersectTool.in_features = pObject;
                    //设置输出路径
                    strOutputPath += strName + "_" + "_intersect.shp";
                    intersectTool.out_feature_class = strOutputPath;
                    //执行求交运算
                    result = gp.Execute(intersectTool, null) as IGeoProcessorResult;
                    break;

                case "叠置求并(Union)":
                    Union unionTool = new Union();
                    //设置输入要素
                    unionTool.in_features = pObject;
                    //设置输出路径
                    strOutputPath += strName + "_" + "_union.shp";
                    unionTool.out_feature_class = strOutputPath;
                    //执行联合运算
                    result = gp.Execute(unionTool, null) as IGeoProcessorResult;
                    break;

                case "叠置标识(Identity)":
                    Identity identityTool = new Identity();
                    //设置输入要素
                    identityTool.in_features       = inputFeat;
                    identityTool.identity_features = overlayFeat;
                    //设置输出路径
                    strOutputPath += strName + "_" + "_identity.shp";
                    identityTool.out_feature_class = strOutputPath;
                    //执行标识运算
                    result = gp.Execute(identityTool, null) as IGeoProcessorResult;
                    break;
                }
            }
            catch (System.Exception ex)
            {
                //添加处理过程消息
                txtMessage.Text += "叠置分析过程出现错误:" + ex.Message + "\r\n";
            }

            //判断叠置分析是否成功
            if (result.Status != ESRI.ArcGIS.esriSystem.esriJobStatus.esriJobSucceeded)
            {
                txtMessage.Text += "叠置失败!";
            }
            else
            {
                this.DialogResult = DialogResult.OK;
                txtMessage.Text  += "叠置成功!";
            }
        }
        public static void ExportLayerToShapefile(string shapePath, string shapeName, ILayer source)
        {
            try
            {
                // cast the selected/requested layer into a feature layer
                ESRI.ArcGIS.Carto.IFeatureLayer featureLayer = (IFeatureLayer)source;
                
                // create a new feature class to feature class converter utility
                ESRI.ArcGIS.ConversionTools.FeatureClassToFeatureClass fc2fc 
                    = new ESRI.ArcGIS.ConversionTools.FeatureClassToFeatureClass();

                // set the input feature layer
                fc2fc.in_features = featureLayer;

                // set the output path and Shapefile name
                fc2fc.out_path = shapePath;
                fc2fc.out_name = shapeName + ".shp";

                // create a new GeoProcessor
                ESRI.ArcGIS.Geoprocessor.Geoprocessor geoprocessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
                geoprocessor.TemporaryMapLayers = true;

                // execute the FeatureClassToFeatureClass
                geoprocessor.Execute(fc2fc, null);

                // export a copy of the layer file definition too for upload/style at a later time
                ESRI.ArcGIS.DataManagementTools.SaveToLayerFile saveToLayerFile 
                    = new ESRI.ArcGIS.DataManagementTools.SaveToLayerFile();
                saveToLayerFile.in_layer = source;
                saveToLayerFile.out_layer = shapePath + "\\" + shapeName + ".lyr";

                // execute the FeatureClassToFeatureClass
                geoprocessor.Execute(saveToLayerFile, null);

                // remove reference to the tool and geoprocessor
                fc2fc = null;
                geoprocessor = null;
            }
            catch (Exception ex)
            {
                // an error occured
                System.Windows.Forms.MessageBox.Show("Error: " + ex.Message);
            }
        }
        //开始分析
        private void btnOK_Click(object sender, EventArgs e)
        {
            //判断是否选择要素
            if (this.txtInputLayer.Text == "" || this.txtInputLayer.Text == null ||
                this.txtOverlayLayer.Text == "" || this.txtOverlayLayer.Text == null)
            {
                txtMessage.Text = "请选择参加叠置分析的图层!";
                return;
            }
            ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            //OverwriteOutput为真时,输出图层会覆盖当前文件夹下的同名图层
            gp.OverwriteOutput = true;

            //设置参与叠置分析的多个对象
            object inputFeat = this.txtInputLayer.Text;
            object overlayFeat = this.txtOverlayLayer.Text;
            IGpValueTableObject pObject = new GpValueTableObjectClass();
            pObject.SetColumns(2);
            pObject.AddRow(ref inputFeat);
            pObject.AddRow(ref overlayFeat);

            //获取要素名称
            string str = System.IO.Path.GetFileName(this.txtInputLayer.Text);
            int index = str.LastIndexOf(".");
            string strName = str.Remove(index);

            //设置输出路径
            strOutputPath = txtOutputLayerPath.Text;

            //叠置分析结果
            IGeoProcessorResult result = null;

            //创建叠置分析实例,执行叠置分析
            string strOverlay = cmbOverlayType.SelectedItem.ToString();
            try
            {
                //添加处理过程消息
                txtMessage.Text = "开始叠置分析……" + "\r\n";
                switch (strOverlay)
                {
                    case "叠置求交(Intersect)":
                        Intersect intersectTool = new Intersect();
                        //设置输入要素
                        intersectTool.in_features = pObject;
                        //设置输出路径
                        strOutputPath += strName + "_" + "_intersect.shp";
                        intersectTool.out_feature_class = strOutputPath;
                        //执行求交运算
                        result = gp.Execute(intersectTool, null) as IGeoProcessorResult;
                        break;
                    case "叠置求并(Union)":
                        Union unionTool = new Union();
                        //设置输入要素
                        unionTool.in_features = pObject;
                        //设置输出路径
                        strOutputPath += strName + "_" + "_union.shp";
                        unionTool.out_feature_class = strOutputPath;
                        //执行联合运算
                        result = gp.Execute(unionTool, null) as IGeoProcessorResult;
                        break;
                    case "叠置标识(Identity)":
                        Identity identityTool = new Identity();
                        //设置输入要素
                        identityTool.in_features = inputFeat;
                        identityTool.identity_features = overlayFeat;
                        //设置输出路径
                        strOutputPath += strName + "_" + "_identity.shp";
                        identityTool.out_feature_class = strOutputPath;
                        //执行标识运算
                        result = gp.Execute(identityTool, null) as IGeoProcessorResult;
                        break;
                }
            }
            catch (System.Exception ex)
            {
                //添加处理过程消息
                txtMessage.Text += "叠置分析过程出现错误:" + ex.Message + "\r\n";
            }

            //判断叠置分析是否成功
            if (result.Status != ESRI.ArcGIS.esriSystem.esriJobStatus.esriJobSucceeded)
                txtMessage.Text += "叠置失败!";
            else
            {
                this.DialogResult = DialogResult.OK;
                txtMessage.Text += "叠置成功!";
            }
        }
예제 #19
0
        //利用quickexport进行数据转换  dwg-->mdb
        private void QuickImportTopdb(string strSrcDwg, string strdesPdb)
        {
            ITrackCancel pTrackCancel = null;

            //找到tool
            ESRI.ArcGIS.Geoprocessor.Geoprocessor _geoPro = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            //ESRI.ArcGIS.Geoprocessing.IGeoProcessor _geoPro = new ESRI.ArcGIS.Geoprocessing.GeoProcessorClass();
            pTrackCancel = new TrackCancelClass();
            IVariantArray pVArray    = new VarArrayClass();
            IVariantArray parameters = new VarArrayClass();

            parameters.Add("ACAD," + strSrcDwg);
            string strtoolName = "";

            //parameters.Add("RUNTIME_MACROS,");
            //parameters.Add("METAFILE,acad,_EXPAND_BLOCKS,yes,ACAD_IN_USE_BLOCK_HEADER_LAYER,yes,"
            //+ "ACAD_IN_RESOLVE_ENTITY_COLOR,yes,_EXPAND_VISIBLE,yes,_READ_AS_2_5D,no,"
            //+ "_BULGES_AS_ARCS,no,_STORE_BULGE_INFO,no,_READ_PAPER_SPACE,no,"
            //+ "ACAD_IN_READ_GROUPS,no,_IGNORE_UCS,no,_ACADPreserveComplexHatches,no,"
            //+ "_MERGE_SCHEMAS,YES,");
            //parameters.Add("META_MACROS,");
            //parameters.Add("Source_EXPAND_BLOCKS,yes,"
            //+ "SourceACAD_IN_USE_BLOCK_HEADER_LAYER,yes,SourceACAD_IN_RESOLVE_ENTITY_COLOR,yes"
            //+ ",Source_EXPAND_VISIBLE,yes,Source_READ_AS_2_5D,no,Source_BULGES_AS_ARCS,no,"
            //+ "Source_STORE_BULGE_INFO,no,Source_READ_PAPER_SPACE,no,SourceACAD_IN_READ_GROUPS,no"
            //+ ",Source_IGNORE_UCS,no,Source_ACADPreserveComplexHatches,no,METAFILE,acad,COORDSYS,,IDLIST,,");
            //parameters.Add("__FME_DATASET_IS_SOURCE__,true");
            //string param = "__FME_DATASET_IS_SOURCE__,true";
            //parameters.Add(param);
            parameters.Add(strdesPdb + "\\..\\tmp.mdb");


            strtoolName = "QuickImport_interop";

            IGPEnvironmentManager pgpEnv = new GPEnvironmentManager();
            IGPMessages           pGpMessages; //= _geoPro.Validate(parameters, false, pgpEnv);
            IGPComHelper          pGPCOMHelper = new GpDispatch();

            //这里是关键,如果不赋值的话,那么就会报错
            IGPEnvironmentManager pEnvMgr = pGPCOMHelper.EnvironmentManager;

            pgpEnv.PersistAll       = true;
            pGpMessages             = new GPMessagesClass();
            _geoPro.OverwriteOutput = true;
            //Execute the model tool by name.
            _geoPro.Execute(strtoolName, parameters, pTrackCancel);
            //QuickImport qi = new QuickImport();
            //qi.Input = txtSource.Text;
            //qi.Output = txtTarget.Text;
            //_geoPro.Execute(qi, pTrackCancel);
            ESRI.ArcGIS.ConversionTools.FeatureClassToShapefile FCTS = new ESRI.ArcGIS.ConversionTools.FeatureClassToShapefile();
            FCTS.Output_Folder = strdesPdb;
            IWorkspaceFactory pWF        = new AccessWorkspaceFactoryClass();
            IWorkspace        pWorkSpace = pWF.OpenFromFile(strdesPdb + "\\..\\tmp.mdb", 0);
            IEnumDatasetName  pED        = pWorkSpace.get_DatasetNames(esriDatasetType.esriDTFeatureClass);
            IDatasetName      pDataSet   = pED.Next();

            while (pDataSet != null)
            {
                if ((pWorkSpace as IFeatureWorkspace).OpenFeatureClass(pDataSet.Name).FeatureType != esriFeatureType.esriFTSimple)//排除注记等
                {
                    pDataSet = pED.Next();
                    continue;
                }
                //_geoPro = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
                //_geoPro.OverwriteOutput = true;
                FCTS.Input_Features = pWorkSpace.PathName + "\\" + pDataSet.Name;
                _geoPro.Execute(FCTS, pTrackCancel);
                pDataSet = pED.Next();
            }


            Stream       s  = new System.IO.FileStream("d:\\qimport.txt", FileMode.Create);
            StreamWriter sw = new StreamWriter(s);

            for (int i = 0; i < _geoPro.MessageCount; i++)
            {
                sw.WriteLine(_geoPro.GetMessage(i));
            }
            sw.Close();
            s.Close();
        }
예제 #20
0
        public void OtherRule(string idname, string checkname, string IN_RuleType, string TABLENAME, string SUPTABLE, string inputtext, IHookHelper m_hookHelper)
        {
            CommonClass common = new CommonClass();

            IFeatureClass     IN_FeatureClass     = common.GetLayerByName(TABLENAME).FeatureClass;
            IGeoDataset       pGeoDataset         = IN_FeatureClass as IGeoDataset;
            ISpatialReference spatialReference    = pGeoDataset.SpatialReference;
            IFeatureClass     IN_Sup_FeatureClass = null;

            if (SUPTABLE != null)
            {
                IN_Sup_FeatureClass = common.GetLayerByName(SUPTABLE).FeatureClass;
            }
            string ErrorFilePath = this.topoDir + "\\" + checkname + idname + ".shp";

            if (IN_RuleType == "面多部件检查")
            {
                try
                {
                    common.CreatShpFile(this.topoDir, spatialReference, esriGeometryType.esriGeometryPolygon, checkname + idname);
                    List <ErrorEntity> list   = new List <ErrorEntity>();
                    IFeatureCursor     cursor = IN_FeatureClass.Search(null, false);
                    int      tempCount        = 0;
                    IFeature pFeature         = cursor.NextFeature();
                    while (pFeature != null)
                    {
                        IGeometry            pGeo          = pFeature.ShapeCopy;
                        ITopologicalOperator pTopoOperator = pGeo as ITopologicalOperator;
                        int iCount = 0;
                        if (IN_FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                        {
                            iCount = (pGeo as IPolygon).ExteriorRingCount;
                        }
                        else if (IN_FeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
                        {
                            iCount = ((pGeo as IPolyline) as IGeometryCollection).GeometryCount;
                        }
                        else if (IN_FeatureClass.ShapeType == esriGeometryType.esriGeometryMultipoint)
                        {
                            iCount = ((pGeo as IMultipoint) as IPointCollection).PointCount;
                        }
                        if (iCount > 1)
                        {
                            tempCount++;
                            common.GenerateSHPFile(pFeature.ShapeCopy, ErrorFilePath);
                        }
                        pFeature = cursor.NextFeature();
                    }
                    //new ErrorTable().AddErr(list, ErrType.MultiPart, idname);
                    if (!DicTopoError.ContainsKey(idname))
                    {
                        DicTopoError.Add(idname, tempCount);
                    }
                    else
                    {
                        DicTopoError[idname] = tempCount;
                    }

                    Marshal.ReleaseComObject(cursor);

                    if (tempCount == 0)
                    {
                        string            shpFolder         = System.IO.Path.GetDirectoryName(ErrorFilePath);
                        IWorkspaceFactory pWorkspaceFac     = new ShapefileWorkspaceFactoryClass();
                        IWorkspace        pWorkSpace        = pWorkspaceFac.OpenFromFile(ErrorFilePath, 0);
                        IFeatureWorkspace pFeatureWorkSpace = pWorkSpace as IFeatureWorkspace;
                        if (System.IO.File.Exists(ErrorFilePath))
                        {
                            IFeatureClass pFCChecker = pFeatureWorkSpace.OpenFeatureClass(ErrorFilePath);
                            if (pFCChecker != null)
                            {
                                IDataset pds = pFCChecker as IDataset;
                                pds.Delete();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(typeof(TopoChecker), ex);
                }
            }
            else if (IN_RuleType == "面自相交检查")
            {
                int errorCount = 0;
                try
                {
                    common.CreatShpFile(this.topoDir, spatialReference, esriGeometryType.esriGeometryPoint, checkname + idname);
                    IFeatureLayer pLayer = new FeatureLayer();
                    pLayer.FeatureClass = IN_FeatureClass;
                    TopoClassChecker topo = new TopoClassChecker();

                    IFeatureCursor cursor;
                    IQueryFilter   filter = new QueryFilterClass();
                    filter.SubFields = pLayer.FeatureClass.OIDFieldName + "," + pLayer.FeatureClass.ShapeFieldName;
                    cursor           = pLayer.FeatureClass.Search(filter, true);
                    IFeature feature = null;
                    object   missing = Type.Missing;
                    while ((feature = cursor.NextFeature()) != null)
                    {
                        IPoint              tempPoint = null;
                        StringBuilder       builder   = new StringBuilder();
                        IGeometryCollection shape     = feature.Shape as IGeometryCollection;
                        for (int i = 0; i < shape.GeometryCount; i++)
                        {
                            esriNonSimpleReasonEnum enum2;
                            IPointCollection        newPoints = shape.get_Geometry(i) as IPointCollection;
                            IRing ring = newPoints as IRing;
                            int   num2 = 0;
                            if (ring.IsClosed)
                            {
                                num2 = 1;
                            }
                            PolylineClass o = new PolylineClass();
                            o.AddPointCollection(newPoints);
                            o.SpatialReference = spatialReference;

                            ITopologicalOperator3 @operator = o;
                            @operator.IsKnownSimple_2 = false;
                            if ([email protected]_IsSimpleEx(out enum2) && (enum2 == esriNonSimpleReasonEnum.esriNonSimpleSelfIntersections))
                            {
                                List <string> list2 = new List <string>();
                                List <string> list3 = new List <string>();
                                for (int j = num2; j < newPoints.PointCount; j++)
                                {
                                    IPoint point = newPoints.get_Point(j);
                                    tempPoint = point;
                                    string item = point.X.ToString() + "," + point.Y.ToString();
                                    if (list2.Contains(item))
                                    {
                                        if (!list3.Contains(item))
                                        {
                                            builder.Append(";");
                                            builder.Append(item);
                                            list3.Add(item);
                                        }
                                    }
                                    else
                                    {
                                        list2.Add(item);
                                    }
                                }
                            }
                            Marshal.ReleaseComObject(o);
                            o = null;
                        }
                        if (builder.Length > 0)
                        {
                            errorCount++;

                            string[] strArray = builder.ToString().Substring(1).Split(new char[] { ';' });
                            ESRI.ArcGIS.Geometry.IPointCollection pPointCollection1 = new ESRI.ArcGIS.Geometry.MultipointClass();
                            foreach (string str in strArray)
                            {
                                if (!string.IsNullOrEmpty(str))
                                {
                                    string[] strArray2 = str.Split(new char[] { ',' });
                                    double   pX        = double.Parse(strArray2[0]);
                                    double   pY        = double.Parse(strArray2[1]);
                                    ESRI.ArcGIS.Geometry.IPoint point = new ESRI.ArcGIS.Geometry.PointClass();
                                    point.X = pX;
                                    point.Y = pY;
                                    common.GenerateSHPFile(point, ErrorFilePath);
                                }
                            }
                        }
                    }
                    Marshal.ReleaseComObject(cursor);
                    if (errorCount == 0)
                    {
                        string            shpFolder         = System.IO.Path.GetDirectoryName(ErrorFilePath);
                        IWorkspaceFactory pWorkspaceFac     = new ShapefileWorkspaceFactoryClass();
                        IWorkspace        pWorkSpace        = pWorkspaceFac.OpenFromFile(ErrorFilePath, 0);
                        IFeatureWorkspace pFeatureWorkSpace = pWorkSpace as IFeatureWorkspace;
                        if (System.IO.File.Exists(ErrorFilePath))
                        {
                            IFeatureClass pFCChecker = pFeatureWorkSpace.OpenFeatureClass(ErrorFilePath);
                            if (pFCChecker != null)
                            {
                                IDataset pds = pFCChecker as IDataset;
                                pds.Delete();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(typeof(TopoChecker), ex);
                }
                if (!DicTopoError.ContainsKey(idname))
                {
                    DicTopoError.Add(idname, errorCount);
                }
                else
                {
                    DicTopoError[idname] = errorCount;
                }
            }
            else if (IN_RuleType == "缝隙检查")
            {
                int errorCount = 0;
                try
                {
                    common.CreatShpFile(this.topoDir, spatialReference, esriGeometryType.esriGeometryPolygon, checkname + idname);
                    this.m_hookHelper = m_hookHelper;
                    IFeatureClass pFClass = IN_FeatureClass;
                    //获取空间参考
                    IGeometry   geometryBag = new GeometryBagClass();
                    IGeoDataset geoDataset  = pFClass as IGeoDataset;
                    geometryBag.SpatialReference = geoDataset.SpatialReference;

                    ////属性过滤
                    IFeatureCursor featureCursor = pFClass.Search(null, false);

                    // 遍历游标
                    IFeature            currentFeature     = featureCursor.NextFeature();
                    IGeometryCollection geometryCollection = geometryBag as IGeometryCollection;
                    object missing = Type.Missing;
                    while (currentFeature != null)
                    {
                        geometryCollection.AddGeometry(currentFeature.Shape, ref missing, ref missing);
                        currentFeature = featureCursor.NextFeature();
                    }

                    // 合并要素
                    ITopologicalOperator unionedPolygon = null;
                    unionedPolygon = new Polygon() as ITopologicalOperator;
                    unionedPolygon.ConstructUnion(geometryCollection as IEnumGeometry);

                    Marshal.ReleaseComObject(featureCursor);
                    IPolygon4           pMergerPolygon     = unionedPolygon as IPolygon4;
                    IGeometryBag        pOutGeometryBag    = pMergerPolygon.ExteriorRingBag; //获取外部环
                    IGeometryCollection pOutGmtyCollection = pOutGeometryBag as IGeometryCollection;

                    for (int i = 0; i < pOutGmtyCollection.GeometryCount; i++)   //对外部环遍历
                    {
                        IGeometry pOutRing = pOutGmtyCollection.get_Geometry(i); //外部环
                        //【此处可以对外部环进行操作】
                        IPointCollection pOutRingCollection = pOutRing as IPointCollection;
                        for (int j = 0; j < pOutRingCollection.PointCount; j++)
                        {
                            IPoint pOutRingPoint = pOutRingCollection.get_Point(j);//获取外环上的点
                        }

                        IGeometryBag        pInteriotGeometryBag        = pMergerPolygon.get_InteriorRingBag(pOutRing as IRing); //获取内部环
                        IGeometryCollection pInteriorGeometryCollection = pInteriotGeometryBag as IGeometryCollection;

                        for (int j = 0; j < pInteriorGeometryCollection.GeometryCount; j++)
                        {
                            ISegmentCollection SegCol = pInteriorGeometryCollection.get_Geometry(j) as ISegmentCollection;

                            IPolygon           PPolygon  = new PolygonClass();
                            ISegmentCollection newSegCol = PPolygon as ISegmentCollection;
                            newSegCol.AddSegmentCollection(SegCol);
                            //pInteriorGeometry即为多边形的内部环
                            IGeometry inRing = PPolygon as IGeometry;
                            inRing.SpatialReference = geometryBag.SpatialReference;
                            IArea  area    = inRing as IArea;
                            Double getarea = System.Math.Abs(Convert.ToDouble(area.Area));
                            if (inputtext == null || inputtext == "" || getarea < Convert.ToDouble(inputtext))
                            {
                                Boolean        flag   = true;
                                ISpatialFilter filter = new SpatialFilterClass();
                                filter.Geometry   = inRing;
                                filter.SubFields  = pFClass.OIDFieldName + "," + pFClass.ShapeFieldName;
                                filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                                IFeatureCursor o       = pFClass.Search(filter, true);
                                IFeature       feature = o.NextFeature();
                                while (feature != null && flag)
                                {
                                    IPolygon4           pPolygon           = feature.Shape as IPolygon4;
                                    IGeometryBag        iOutGeometryBag    = pPolygon.ExteriorRingBag; //获取外部环
                                    IGeometryCollection iOutGmtyCollection = iOutGeometryBag as IGeometryCollection;

                                    for (int m = 0; m < iOutGmtyCollection.GeometryCount && flag; m++)  //对外部环遍历
                                    {
                                        IGeometry           outGeo     = iOutGmtyCollection.get_Geometry(m);
                                        IGeometryCollection polyGonGeo = new PolygonClass();
                                        polyGonGeo.AddGeometry(outGeo);
                                        IPolygon iPolygon = polyGonGeo as IPolygon;
                                        iPolygon.SimplifyPreserveFromTo();
                                        IRelationalOperator2 pRelationalOperator2 = iPolygon as IRelationalOperator2;
                                        if (!pRelationalOperator2.Contains(inRing))
                                        {
                                            errorCount++;
                                            common.GenerateSHPFile(inRing, ErrorFilePath);
                                            flag = false;
                                        }
                                    }
                                    feature = o.NextFeature();
                                }
                                Marshal.ReleaseComObject(o);
                            }
                        }
                        if (errorCount == 0)
                        {
                            string            shpFolder         = System.IO.Path.GetDirectoryName(ErrorFilePath);
                            IWorkspaceFactory pWorkspaceFac     = new ShapefileWorkspaceFactoryClass();
                            IWorkspace        pWorkSpace        = pWorkspaceFac.OpenFromFile(ErrorFilePath, 0);
                            IFeatureWorkspace pFeatureWorkSpace = pWorkSpace as IFeatureWorkspace;
                            if (System.IO.File.Exists(ErrorFilePath))
                            {
                                IFeatureClass pFCChecker = pFeatureWorkSpace.OpenFeatureClass(ErrorFilePath);
                                if (pFCChecker != null)
                                {
                                    IDataset pds = pFCChecker as IDataset;
                                    pds.Delete();
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(typeof(TopoChecker), ex);
                }
                if (!DicTopoError.ContainsKey(idname))
                {
                    DicTopoError.Add(idname, errorCount);
                }
                else
                {
                    DicTopoError[idname] = errorCount;
                }
            }
            else if (IN_RuleType == "面重叠检查")
            {
                IFeatureClass outIFC = null;
                this.m_hookHelper = m_hookHelper;
                ESRI.ArcGIS.AnalysisTools.Intersect intersect = new ESRI.ArcGIS.AnalysisTools.Intersect();
                string outString = this.topoDir + "\\" + checkname + idname + ".shp";
                intersect.in_features       = common.GetPathByName(TABLENAME);
                intersect.out_feature_class = outString;
                Geoprocessor geoProcessor = new Geoprocessor();
                geoProcessor.OverwriteOutput = true;
                try
                {
                    if (this.gp == null)
                    {
                        this.gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
                    }
                    IGeoProcessorResult result = (IGeoProcessorResult)this.gp.Execute(intersect, null);

                    if (result.Status != ESRI.ArcGIS.esriSystem.esriJobStatus.esriJobSucceeded)
                    {
                        Console.WriteLine("gp工具执行错误");
                    }
                    else
                    {
                        outIFC = this.gp.Open(result.ReturnValue) as IFeatureClass;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(typeof(TopoChecker), ex);
                    Console.WriteLine(ex.Message);
                }

                if (outIFC.FeatureCount(null) == 0)
                {
                    string            shpFolder         = System.IO.Path.GetDirectoryName(ErrorFilePath);
                    IWorkspaceFactory pWorkspaceFac     = new ShapefileWorkspaceFactoryClass();
                    IWorkspace        pWorkSpace        = pWorkspaceFac.OpenFromFile(ErrorFilePath, 0);
                    IFeatureWorkspace pFeatureWorkSpace = pWorkSpace as IFeatureWorkspace;
                    if (System.IO.File.Exists(ErrorFilePath))
                    {
                        IFeatureClass pFCChecker = pFeatureWorkSpace.OpenFeatureClass(ErrorFilePath);
                        if (pFCChecker != null)
                        {
                            IDataset pds = pFCChecker as IDataset;
                            pds.Delete();
                        }
                    }
                }

                if (!DicTopoError.ContainsKey(idname))
                {
                    DicTopoError.Add(idname, outIFC.FeatureCount(null));
                }
                else
                {
                    DicTopoError[idname] = outIFC.FeatureCount(null);
                }
            }
            else if (IN_RuleType == "面重叠检查(与其他图层)")
            {
                IFeatureClass outIFC = null;
                this.m_hookHelper = m_hookHelper;
                ESRI.ArcGIS.AnalysisTools.Intersect intersect = new ESRI.ArcGIS.AnalysisTools.Intersect();
                string outString = this.topoDir + "\\" + checkname + idname + ".shp";
                intersect.in_features       = @common.GetPathByName(TABLENAME) + ";" + @common.GetPathByName(SUPTABLE);
                intersect.out_feature_class = outString;
                Geoprocessor geoProcessor = new Geoprocessor();
                geoProcessor.OverwriteOutput = true;
                try
                {
                    if (this.gp == null)
                    {
                        this.gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
                    }
                    IGeoProcessorResult result = (IGeoProcessorResult)this.gp.Execute(intersect, null);

                    if (result.Status != ESRI.ArcGIS.esriSystem.esriJobStatus.esriJobSucceeded)
                    {
                        Console.WriteLine("gp工具执行错误");
                    }
                    else
                    {
                        outIFC = this.gp.Open(result.ReturnValue) as IFeatureClass;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    LogHelper.WriteLog(typeof(TopoChecker), ex);
                }
                if (outIFC.FeatureCount(null) == 0)
                {
                    string            shpFolder         = System.IO.Path.GetDirectoryName(ErrorFilePath);
                    IWorkspaceFactory pWorkspaceFac     = new ShapefileWorkspaceFactoryClass();
                    IWorkspace        pWorkSpace        = pWorkspaceFac.OpenFromFile(ErrorFilePath, 0);
                    IFeatureWorkspace pFeatureWorkSpace = pWorkSpace as IFeatureWorkspace;
                    if (System.IO.File.Exists(ErrorFilePath))
                    {
                        IFeatureClass pFCChecker = pFeatureWorkSpace.OpenFeatureClass(ErrorFilePath);
                        if (pFCChecker != null)
                        {
                            IDataset pds = pFCChecker as IDataset;
                            pds.Delete();
                        }
                    }
                }
                if (!DicTopoError.ContainsKey(idname))
                {
                    DicTopoError.Add(idname, outIFC.FeatureCount(null));
                }
                else
                {
                    DicTopoError[idname] = outIFC.FeatureCount(null);
                }
            }
            Marshal.ReleaseComObject(IN_FeatureClass);
            if (SUPTABLE != null)
            {
                Marshal.ReleaseComObject(IN_Sup_FeatureClass);
            }
        }
        //Creates raster catalog using GP CreateRasterCatalog class
        static void CreateRasterCatalog_GP(object rasterCoordSys, object geometryCoordsys)
        {
            //Initialize GeoProcessor
            ESRI.ArcGIS.Geoprocessor.Geoprocessor geoProcessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();

            //CreateRasterCatalog GP tool
            CreateRasterCatalog createRasterCatalog = new CreateRasterCatalog();

            //Set parameters
            createRasterCatalog.out_path = sdePath;
            createRasterCatalog.out_name = catalogName;
            createRasterCatalog.raster_spatial_reference = rasterCoordSys;
            createRasterCatalog.spatial_reference = geometryCoordsys;

            //Execute the tool to create a raster catalog
            geoProcessor.Execute(createRasterCatalog, null);
            ReturnMessages(geoProcessor);
        }
예제 #22
0
        private static void RunGPFieldMapping()
        {
            // Initialize the Geoprocessor
            ESRI.ArcGIS.Geoprocessor.Geoprocessor GP = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
            GP.OverwriteOutput = true;

            // Create the GPUtilites object
            IGPUtilities gputilities = new GPUtilitiesClass();

            // Create a DETable data element object
            IDETable inputTableA = (IDETable)gputilities.MakeDataElement(@"C:\data\citiblocks.gdb\census", null, null);

            // Create an array of input tables
            IArray inputtables = new ArrayClass();

            inputtables.Add(inputTableA);

            // Initialize the GPFieldMapping
            IGPFieldMapping fieldmapping = new GPFieldMappingClass();

            fieldmapping.Initialize(inputtables, null);

            // Create a new output field
            IFieldEdit trackidfield = new FieldClass();

            trackidfield.Name_2   = "TRACTID";
            trackidfield.Type_2   = esriFieldType.esriFieldTypeString;
            trackidfield.Length_2 = 50;

            // Create a new FieldMap
            IGPFieldMap trackid = new GPFieldMapClass();

            trackid.OutputField = trackidfield;

            // Find field map "STFID" containing the input field "STFID". Add input field to the new field map.
            int         fieldmap_index = fieldmapping.FindFieldMap("STFID");
            IGPFieldMap stfid_fieldmap = fieldmapping.GetFieldMap(fieldmap_index);
            int         field_index    = stfid_fieldmap.FindInputField(inputTableA, "STFID");
            IField      inputField     = stfid_fieldmap.GetField(field_index);

            trackid.AddInputField(inputTableA, inputField, 5, 10);

            // Add the new field map to the field mapping
            fieldmapping.AddFieldMap(trackid);

            // Execute Table to Table tool using the FieldMapping
            TableToTable tblTotbl = new TableToTable();

            tblTotbl.in_rows       = inputTableA;
            tblTotbl.out_path      = @"C:\data\citiblocks.gdb";
            tblTotbl.out_name      = "census_out";
            tblTotbl.field_mapping = fieldmapping;

            object sev = null;

            try
            {
                GP.Execute(tblTotbl, null);
                System.Windows.Forms.MessageBox.Show(GP.GetMessages(ref sev));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                System.Windows.Forms.MessageBox.Show(GP.GetMessages(ref sev));
            }
        }
예제 #23
0
        void GPIntsect()
        {
            ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();

            ESRI.ArcGIS.AnalysisTools.Intersect pIntsect = new ESRI.ArcGIS.AnalysisTools.Intersect();

            gp.OverwriteOutput = true;
            //设置工作空间 // IGpEnumList gpEnumEnv = gp.ListEnvironments("*");
            gp.SetEnvironmentValue("workspace", @".\data\分析用的空间数据");

            pIntsect.in_features = ".\data分析用的空间数据\\县界面.shp;.\data分析用的空间数据\\地级市.shp";

            pIntsect.out_feature_class = "Result.shp";

            pIntsect.cluster_tolerance = 0.5;

            pIntsect.join_attributes = "All";

            pIntsect.output_type = "INPUT";

            gp.Execute(pIntsect, null);
        }