Example #1
0
        //浏览文件夹选择文件gdb
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            string path = "";
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            folderBrowserDialog.ShowNewFolderButton = false;
            folderBrowserDialog.Description         = "选择.gdb文件数据库";
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                path = folderBrowserDialog.SelectedPath;
                if (path.Substring((path.Length) - 4) != ".gdb")
                {
                    MessageBox.Show("请选择*.gdb文件地理数据库!", "提示");
                    return;
                }
                tbxGDBPath.Text            = path;
                GlobalTopoVaribate.GDBPath = path;
            }
            if (path == "")
            {
                return;
            }
            IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactory();
            IWorkspace        pWorkspace        = pWorkspaceFactory.OpenFromFile(path, 0);

            FeatureDSList = getGDBFeatureDS(pWorkspace);
            GlobalTopoVaribate.GFeatureDSList = FeatureDSList;
            cbxFeatureDS.Properties.Items.Clear();
            cbxFeatureDS.Text = "";
            foreach (IFeatureDataset pFeatureDS in FeatureDSList)
            {
                cbxFeatureDS.Properties.Items.Add(pFeatureDS.Name);
            }
        }
Example #2
0
        private GdbAccess()
        {
            string            calcGdb          = MilSpaceConfiguration.ConnectionProperty.TemporaryGDBConnection;
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();

            calcWorkspace = workspaceFactory.OpenFromFile(calcGdb, 0);
        }
Example #3
0
        // Get the filegeodatabase workspace.
        public IWorkspace GetOutputWorkspace()
        {
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(_options.OutputGeodatabase + "NextGenRoadLoader.gdb", 0);

            //IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace;
            return(workspace);
        }
Example #4
0
        //读取geodatabase数据的方法
        public IFeatureClass OpenGDBFeatureClass(string dbPath, string clsName)
        {
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(dbPath, 0);
            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;
            IFeatureClass     featureClass     = featureWorkspace.OpenFeatureClass(clsName);

            return(featureClass);
        }
        private void btn_read_Click(object sender, EventArgs e)
        {
            // Считываю слои из базы и заполняю CheckBoxList
            clb1.Items.Clear();
            IFeatureClass     myFeatureClass   = null;
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(txtb1.Text, 0);
            IFeatureWorkspace iworkspace       = (IFeatureWorkspace)workspace;
            IEnumDataset      enumDataset      = workspace.get_Datasets(esriDatasetType.esriDTAny);

            enumDataset.Reset();
            List <string> datasets = new List <string>();
            IDataset      dataset  = null;

            while ((dataset = enumDataset.Next()) != null)
            {
                if (dataset.Type == esriDatasetType.esriDTFeatureClass)
                {
                    clb1.Items.Add(dataset.Name);
                }
                if (dataset.Type == esriDatasetType.esriDTFeatureDataset)
                {
                    datasets.Add(dataset.Name);
                }
                //Проходим по датасетам если они есть

                foreach (string el in datasets)
                {
                    string          datasetsroot = txtb1.Text + @"\" + el;
                    IFeatureDataset mydataset    = iworkspace.OpenFeatureDataset(el);
                    IEnumDataset    enumDataset1 = mydataset.Subsets;
                    IDataset        dataset1     = null;
                    while ((dataset1 = enumDataset1.Next()) != null)
                    {
                        clb1.Items.Add(dataset1.Name);
                    }
                }
            }
            // Считываю все поля из всех слоев
            clb2.Items.Clear();
            List <string> bn = new List <string>();

            foreach (object item in clb1.Items)
            {
                myFeatureClass = iworkspace.OpenFeatureClass(item.ToString());
                for (int j = 0; j < myFeatureClass.Fields.FieldCount; j++)
                {
                    bn.Add(myFeatureClass.Fields.get_Field(j).Name);
                }
            }
            string[] bnn = bn.Distinct().ToArray();

            foreach (string f in bnn)
            {
                clb2.Items.Add(f);
            }
        }
Example #6
0
        public static ITable open_table(string ws, string name)
        {
            IWorkspaceFactory GdbWsF = new FileGDBWorkspaceFactory();
            IWorkspace        GdbWs  = GdbWsF.OpenFromFile(ws, 0);
            // open fcs
            IFeatureWorkspace FeatWs = GdbWs as IFeatureWorkspace;
            ITable            table  = FeatWs.OpenTable(name);

            return(table);
        }
Example #7
0
        public static IFeatureClass open_fc(string ws, string name)
        {
            IWorkspaceFactory GdbWsF = new FileGDBWorkspaceFactory();
            IWorkspace        GdbWs  = GdbWsF.OpenFromFile(ws, 0);
            // open fcs
            IFeatureWorkspace FeatWs = GdbWs as IFeatureWorkspace;
            IFeatureClass     fc     = FeatWs.OpenFeatureClass(name);

            return(fc);
        }
        /// <summary>
        /// Creates the output featureclass, either fgdb featureclass or a shapefile
        /// </summary>
        /// <param name="outputPath">location of featureclass</param>
        /// <param name="saveAsType">Type of output selected, either fgdb featureclass or shapefile</param>
        /// <param name="graphicsList">List of graphics for selected tab</param>
        /// <param name="ipSpatialRef">Spatial Reference being used</param>
        /// <returns>Output featureclass</returns>
        public IFeatureClass CreateFCOutput(string outputPath, SaveAsType saveAsType, List <Graphic> graphicsList, ISpatialReference ipSpatialRef)
        {
            string        fcName     = System.IO.Path.GetFileName(outputPath);
            string        folderName = System.IO.Path.GetDirectoryName(outputPath);
            IFeatureClass fc         = null;

            try
            {
                bool isGraphicLineOrRangeRing = graphicsList[0].GraphicType == GraphicTypes.Line || graphicsList[0].GraphicType == GraphicTypes.RangeRing;
                if (saveAsType == SaveAsType.FileGDB)
                {
                    IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
                    IWorkspace        workspace        = workspaceFactory.OpenFromFile(folderName, 0);
                    IFeatureWorkspace fWorkspace       = (IFeatureWorkspace)workspace;

                    if (DoesFeatureClassExist(folderName, fcName))
                    {
                        DeleteFeatureClass(fWorkspace, fcName);
                    }

                    fc = CreateFeatureClass(fWorkspace, fcName, isGraphicLineOrRangeRing);

                    foreach (Graphic graphic in graphicsList)
                    {
                        IFeature feature = fc.CreateFeature();

                        if (graphic.GraphicType != GraphicTypes.Line && graphic.GraphicType != GraphicTypes.RangeRing)
                        {
                            feature.Shape = PolylineToPolygon(graphic.Geometry);
                        }
                        else
                        {
                            feature.Shape = graphic.Geometry;
                        }

                        feature.Store();
                    }
                }
                else if (saveAsType == SaveAsType.Shapefile)
                {
                    // already asked them for confirmation to overwrite file
                    if (File.Exists(outputPath))
                    {
                        DeleteShapeFile(outputPath);
                    }

                    fc = ExportToShapefile(outputPath, graphicsList, ipSpatialRef, isGraphicLineOrRangeRing);
                }
                return(fc);
            }
            catch (Exception ex)
            {
                return(fc);
            }
        }
Example #9
0
File: Home.cs Project: gistop/aegis
 private void AddGDB()
 {
     FileGDBWorkspaceFactory pWSF = new FileGDBWorkspaceFactory();
     IFeatureWorkspace pWS1 = pWSF.OpenFromFile("C:\\temp\\gdb.gdb", 0) as IFeatureWorkspace;
     IFeatureClass featureclass = pWS1.OpenFeatureClass("layer");
     IFeatureLayer pFLRoads = new FeatureLayer();
     pFLRoads.FeatureClass = featureclass;
     pFLRoads.Name = "点";
     ILayer pLayerRoads = pFLRoads as ILayer;
     Global.mainmap.AddLayer(pLayerRoads);
 }
Example #10
0
        private GdbAccess()
        {
            string            calcGdb          = MilSpaceConfiguration.ConnectionProperty.TemporaryGDBConnection;
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();

            logger.InfoEx($"Opening access to {calcGdb}.");
            calcWorkspace = workspaceFactory.OpenFromFile(calcGdb, 0);
            if (calcWorkspace == null)
            {
                logger.ErrorEx($"Cannot access to {calcGdb}.");
            }
        }
        private void btnQuery_Click(object sender, EventArgs e)
        {
            string year  = cbxYear.SelectedItem.ToString();
            string month = cbxMonth.SelectedItem.ToString();

            IWorkspaceFactory pFileGDBWorkspaceFactory;

            pFileGDBWorkspaceFactory = new FileGDBWorkspaceFactory();
            IWorkspace   pWorkspace   = pFileGDBWorkspaceFactory.OpenFromFile(rasterPath, 0);
            IEnumDataset pEnumDataset = pWorkspace.get_Datasets(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTAny);

            pEnumDataset.Reset();
            IDataset  pDataset        = pEnumDataset.Next();
            DataTable SpatialRefTable = new DataTable();

            SpatialRefTable.Columns.Add(new DataColumn("影像名称", typeof(string)));
            SpatialRefTable.Columns.Add(new DataColumn("影像拍摄时间", typeof(string)));

            //判断数据集是否有数据
            while (pDataset != null)
            {
                if (pDataset is IRasterDataset) //栅格数据集
                {
                    IRasterWorkspaceEx pRasterWorkspace = (IRasterWorkspaceEx)pWorkspace;
                    IRasterDataset     pRasterDataset   = pRasterWorkspace.OpenRasterDataset(pDataset.Name);
                    //影像金字塔判断与创建
                    ISpatialReference pSpatialRef = (pRasterDataset as IGeoDataset).SpatialReference;
                    string            spatialref  = pSpatialRef.Name.ToString();
                    string            rastername  = pDataset.Name.ToString();
                    string[]          strArray    = rastername.Split('_');

                    DataRow dr = SpatialRefTable.NewRow();
                    dr["影像名称"]   = pDataset.Name.ToString();
                    dr["影像拍摄时间"] = strArray[1].Substring(0, 8);
                    IRasterLayer pRasterLayer = new RasterLayer();
                    pRasterLayer.CreateFromDataset(pRasterDataset);
                    if (strArray[1].Substring(0, 6) == year + month)
                    {
                        SpatialRefTable.Rows.Add(dr);
                    }
                }
                pDataset = pEnumDataset.Next();
            }
            // ExportExcel(SpatialRefTable);
            //弹出显示框
            FormQueryShowResult timeQuery = new FormQueryShowResult();

            timeQuery.Text = "时间查询";
            timeQuery.dgvQueryResult.DataSource       = SpatialRefTable;
            timeQuery.dgvQueryResult.Columns[1].Width = 200;
            timeQuery.Show();
        }
        protected override void OnClick()
        {
            IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactory();

            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(@"D:\Applications\ArcObjects\TestButton\GeoDP\GeoDB.gdb", ArcMap.Application.hWnd);

            IWorkspaceDomains pWorkspaceDomains = pWorkspace as IWorkspaceDomains;
            ICodedValueDomain pDomain           = pWorkspaceDomains.DomainByName["Resturants"] as ICodedValueDomain;

            for (int i = 0; i < pDomain.CodeCount; i++)
            {
                MessageBox.Show("Code: " + pDomain.Value[i] + Environment.NewLine + "Description: " + pDomain.Name[i]);
            }
        }
        /// <summary>
        /// Retrieves all datasets names from filegdb
        /// </summary>
        /// <param name="gdbFilePath">Path to filegdb</param>
        /// <returns>List of names of all featureclasses in filegdb</returns>
        private List <string> GetAllDatasetNames(string gdbFilePath)
        {
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(gdbFilePath, 0);
            IEnumDataset      enumDataset      = workspace.get_Datasets(esriDatasetType.esriDTAny);
            List <string>     names            = new List <string>();
            IDataset          dataset          = null;

            while ((dataset = enumDataset.Next()) != null)
            {
                names.Add(dataset.Name);
            }
            return(names);
        }
Example #14
0
        public static IFeatureClass GetFeatureClass(string GDBpath, string FCname)
        {
            //创建最后所需的点图层
            IFeatureClass feaclass = null;

            //创建工作空间
            FileGDBWorkspaceFactory fileGDBWorkspaceFactory = new FileGDBWorkspaceFactory();
            IWorkspace        workspace        = fileGDBWorkspaceFactory.OpenFromFile(GDBpath, 0);
            IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;

            feaclass = featureWorkspace.OpenFeatureClass(FCname);

            return(feaclass);
        }
Example #15
0
        public static List <string> list_fcs_in_gdb(string ws)
        {
            List <string>     fc_names = new List <string>();
            IWorkspaceFactory GdbWsF   = new FileGDBWorkspaceFactory();
            IWorkspace        GdbWs    = GdbWsF.OpenFromFile(ws, 0);
            IEnumDatasetName  ds_names = GdbWs.get_DatasetNames(esriDatasetType.esriDTFeatureClass);
            IDatasetName      ds_name  = ds_names.Next();

            while (ds_name != null)
            {
                fc_names.Add(ds_name.Name);
                ds_name = ds_names.Next();
            }
            return(fc_names);
        }
Example #16
0
        public static IWorkspace connectSde(string path)
        {
            try
            {
                //定义工作空间,工作空间的数据源来自SDE,IWorkspaceFactory是Geodatabase的入口
                //Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory");
                //IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);

                IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();

                ////通过IPropertySet设置通过SDE连接数据库的各种参数
                //IPropertySet propertySet = new PropertySetClass();
                //propertySet.SetProperty("SERVER", "10.64.192.51");
                //propertySet.SetProperty("SERVICE", "esri_sde");
                //propertySet.SetProperty("INSTANCE", "sde:sqlserver:10.64.192.51");
                ////propertySet.SetProperty("Instance", "port:5151");
                //propertySet.SetProperty("DATABASE", "GasEarlyWarningGIS");
                //propertySet.SetProperty("USER", "sde");
                //propertySet.SetProperty("PASSWORD", "sde");
                //propertySet.SetProperty("VERSION", "sde.DEFAULT");

                ////通过以上设置的参数将数据库的数据通过SDE读入工作空间
                IWorkspace workspace = workspaceFactory.OpenFromFile(path, 0);
                //IWorkspace workspace = null;

                //ILayer pLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap,"点");

                //IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;

                //IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
                //IDataset pDataset = (IDataset)pFeatureClass;
                //workspace = pDataset.Workspace;
                //IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass();
                //workspace = workspaceFactory.Open(ConnectSDE(true), 0);
                return(workspace);



                //return GetSDEWorkspace();
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库连接失败!" + ex.Message);
            }

            return(null);
        }
Example #17
0
        public IWorkspace get_FWorkSp()
        {
            IWorkspaceFactory pWorkSpaceFactory = new FileGDBWorkspaceFactory();
            string            tempFP            = openFGDB();

            if (tempFP != null)
            {
                IWorkspace pWorkSpace = pWorkSpaceFactory.OpenFromFile(tempFP, 0);
                //IEnumDataset pEDataset =pWorkSpace. get_Datasets(esriDatasetType.esriDTAny);
                //IDataset pDataset = pEDataset.Next();
                return(pWorkSpace);
            }
            else
            {
                return(null);
            }
        }
Example #18
0
        private void barButtonItem6_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FolderBrowserDialog openDLG = new FolderBrowserDialog();                                                 //创建文件夹浏览对话框

            if (openDLG.ShowDialog() == DialogResult.OK)                                                             //打开对话框,选择文件夹后,若点击ok按钮
            {
                string sFilePath = openDLG.SelectedPath;                                                             //获得选择的文件夹

                IWorkspaceFactory pWorkspaceFectory = new FileGDBWorkspaceFactory();                                 // 创建能够打开文件型数据库的工作空间工厂对象
                IWorkspace        pWorkspace        = pWorkspaceFectory.OpenFromFile(sFilePath, 0);                  //打开对应的文件夹,返回工作空间对象
                IEnumDataset      pEnumDataset      = pWorkspace.get_Datasets(esriDatasetType.esriDTFeatureDataset); //获取文件数据库中的所有矢量特征数据集集合

                pEnumDataset.Reset();                                                                                //指向矢量特征数据集集合头部
                IDataset pDataset = pEnumDataset.Next();                                                             //获取第一个矢量特征数据集
                while (pDataset != null)                                                                             //若矢量特征数据集非空
                {
                    if (pDataset is IFeatureDataset)                                                                 // 当前矢量特征数据集是否为FeatureDataset
                    {
                        IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;                       //接口转换为IFeatureWorkspace
                        IFeatureDataset   pFeatureDaset     = pFeatureWorkspace.OpenFeatureDataset(pDataset.Name);   //打开当前矢量特征数据集
                        IEnumDataset      pSubEnumdataset   = pFeatureDaset.Subsets;                                 //获取其子数据集
                        pSubEnumdataset.Reset();                                                                     //指向子数据集头部
                        IDataset pSubDataset = pSubEnumdataset.Next();                                               //获取子数据集的第一个数据集
                        while (pSubDataset != null && pSubDataset is IFeatureClass)                                  //当新获取的这个新数据集是FeatureClass
                        {
                            IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(pSubDataset.Name);      // 打开该IFeatureClass
                            IFeatureLayer pLayer        = new FeatureLayer();                                        //创建一个矢量特征层
                            pLayer.FeatureClass = pFeatureClass;                                                     //给该层数据源赋值
                            axMapControl1.Map.AddLayer(pLayer as ILayer);                                            //添加到地图控件中
                            pSubDataset = pSubEnumdataset.Next();                                                    //获取下一个新的子数据集
                        }
                    }
                    else if (pDataset is IFeatureClass)                                                          //当前矢量特征数据集是否为FeatureClass
                    {
                        IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;                   //接口转换为IFeatureWorkspace
                        IFeatureClass     pFeatureClass     = pFeatureWorkspace.OpenFeatureClass(pDataset.Name); // 打开该IFeatureClass
                        IFeatureLayer     pLayer            = new FeatureLayer();                                //创建一个矢量特征层
                        pLayer.FeatureClass = pFeatureClass;                                                     //给该层数据源赋值
                        axMapControl1.Map.AddLayer(pLayer as ILayer);                                            //添加到地图控件中
                    }
                    pDataset = pEnumDataset.Next();                                                              //获取下一个数据集
                }
                axMapControl1.ActiveView.Refresh();                                                              //地图刷新
            }
            //添加GDB
        }
        public static IWorkspace connectSde(string path)
        {
            try
            {
                //定义工作空间,工作空间的数据源来自SDE,IWorkspaceFactory是Geodatabase的入口
                //Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory");
                //IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);

                IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();

                ////通过IPropertySet设置通过SDE连接数据库的各种参数
                //IPropertySet propertySet = new PropertySetClass();
                //propertySet.SetProperty("SERVER", "10.64.192.51");
                //propertySet.SetProperty("SERVICE", "esri_sde");
                //propertySet.SetProperty("INSTANCE", "sde:sqlserver:10.64.192.51");
                ////propertySet.SetProperty("Instance", "port:5151");
                //propertySet.SetProperty("DATABASE", "GasEarlyWarningGIS");
                //propertySet.SetProperty("USER", "sde");
                //propertySet.SetProperty("PASSWORD", "sde");
                //propertySet.SetProperty("VERSION", "sde.DEFAULT");

                ////通过以上设置的参数将数据库的数据通过SDE读入工作空间
                IWorkspace workspace = workspaceFactory.OpenFromFile(path, 0);
                //IWorkspace workspace = null;

                //ILayer pLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap,"点");

                //IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;

                //IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
                //IDataset pDataset = (IDataset)pFeatureClass;
                //workspace = pDataset.Workspace;
                //IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass();
                //workspace = workspaceFactory.Open(ConnectSDE(true), 0);
                return workspace;

                //return GetSDEWorkspace();
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库连接失败!" + ex.Message);
            }

            return null;
        }
        //选择数据集路径
        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            folderBrowserDialog.Description         = "选择文件GDB";
            folderBrowserDialog.ShowNewFolderButton = false;
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                if (folderBrowserDialog.SelectedPath.Substring(folderBrowserDialog.SelectedPath.LastIndexOf(".")) != ".gdb")
                {
                    MessageBox.Show("请选择正确的地理数据库");
                    return;
                }
                IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactory();
                pWorkspace    = pWorkspaceFactory.OpenFromFile(folderBrowserDialog.SelectedPath, 0);
                textBox1.Text = folderBrowserDialog.SelectedPath;
            }
        }
Example #21
0
        protected override void OnClick()
        {
            //
            //  TODO: Sample code showing how to access button host
            //
            IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactory();
            IWorkspace        pWorkspace        = pWorkspaceFactory.OpenFromFile(@"C:\IGeometry\IGeometryGDB\IGeometry.gdb", ArcMap.Application.hWnd);

            IWorkspaceDomains pWorkspaceDomains = pWorkspace as IWorkspaceDomains;
            ICodedValueDomain pDomain           = pWorkspaceDomains.DomainByName["RestaurantTypes"] as ICodedValueDomain;

            for (int i = 0; i < pDomain.CodeCount; i++)
            {
                MessageBox.Show("Code: " + pDomain.Value[i] + Environment.NewLine + "Description: " + pDomain.Name[i]);
            }

            ArcMap.Application.CurrentTool = null;
        }
        private void btn_start_Click(object sender, EventArgs e)
        {
            txb2.Text = "";
            foreach (object itemChecked in clb1.CheckedItems)
            {
                int vsego = 0;
                IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
                IWorkspace        workspace        = workspaceFactory.OpenFromFile(txtb1.Text, 0);
                IFeatureWorkspace iworkspace       = (IFeatureWorkspace)workspace;
                IFeatureClass     myFeatureClass2  = iworkspace.OpenFeatureClass(itemChecked.ToString());
                txb2.Text += itemChecked.ToString() + ":" + "\n";
                //MessageBox.Show(myFeatureClass2.AliasName);
                foreach (object itemChecked2 in clb2.CheckedItems)
                {
                    int fieldind_obj = myFeatureClass2.Fields.FindField(itemChecked2.ToString());

                    if (fieldind_obj >= 0)
                    {
                        IFeatureCursor myFC = myFeatureClass2.Search(null, true);
                        IFeature       curfeature;
                        while ((curfeature = myFC.NextFeature()) != null)
                        {
                            object fieldValue_obj = curfeature.get_Value(fieldind_obj);

                            if ((System.IO.Directory.Exists(fieldValue_obj.ToString()) == false) && (System.IO.File.Exists(fieldValue_obj.ToString()) == false))
                            {
                                txb2.Text += curfeature.OID.ToString() + " " + itemChecked2.ToString() + " не существует файла или папки:" + fieldValue_obj.ToString() + Environment.NewLine;
                                vsego++;
                            }
                        }
                    }
                }
                if (vsego == 0)
                {
                    txb2.Text += "Ok";
                }
                else
                {
                    txb2.Text += "Всего ошибок: " + vsego.ToString();
                }
            }
        }
Example #23
0
        public static IWorkspace OpenFileGDB(string string_0)
        {
            IWorkspace        workspace = null;
            IWorkspaceFactory o         = new FileGDBWorkspaceFactory() as IWorkspaceFactory;

            try
            {
                workspace = o.OpenFromFile(string_0, 0);
            }
            catch (COMException exception)
            {
                MessageBox.Show("错误代码:" + exception.ErrorCode.ToString() + "\r\n" + exception.Message);
            }
            catch (Exception)
            {
            }
            ComReleaser.ReleaseCOMObject(o);
            o = null;
            return(workspace);
        }
Example #24
0
        //既然只是为了获取文件名的列表,不用工作空间也行吧?。。(对esri接口功能不熟悉不了解)
        private void btn_save_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)                           //傻逼问题自己想清楚了
            {
                string strPath = fbd.SelectedPath;
                text_path.Text = fbd.SelectedPath;
                IWorkspaceFactory pWksFactory = new FileGDBWorkspaceFactory();
                IWorkspace        pWorkspace  = pWksFactory.OpenFromFile(strPath, 0); //这里不是读取过了吗??已经读进来还要加加载的操作吗?注意只是打开,你看shapefile的这步之后还要转换接口,引用接口的OpenFeatureClass()方法,可以理解为只是定义了工作空间的路径
                IEnumDataset      pEnumDS     = pWorkspace.get_Datasets(esriDatasetType.esriDTFeatureClass);
                pEnumDS.Reset();
                while (pEnumDS.Next() != null)       //?
                {
                    IDataset dataset = pEnumDS.Next();
                    string   strName = dataset.Name;
                    listV_path.Items.Add(strName);
                }
            }
        }
Example #25
0
        // Create 3 feature classes to hold the point, polyline, and polygon transactions
        private Dictionary <esriGeometryType, IFeatureClass> CreateFCS(string path)
        {
            // Connect to the output file GDB
            IWorkspaceFactory wsFact = new FileGDBWorkspaceFactory();
            IWorkspace        ws     = wsFact.OpenFromFile(path, this.Handle.ToInt32());
            IFeatureWorkspace featws = ws as IFeatureWorkspace;

            // Get the coded value domain for the transaction type, creating if necessary
            IDomain domain = GetOrCreateDomain(ws);

            Dictionary <esriGeometryType, IFeatureClass> dictionary = new Dictionary <esriGeometryType, IFeatureClass>();

            foreach (var geomType in new esriGeometryType[] { esriGeometryType.esriGeometryPoint, esriGeometryType.esriGeometryPolyline, esriGeometryType.esriGeometryPolygon })
            {
                // Create the feature classes
                string fcName   = Enum.GetName(typeof(esriGeometryType), geomType) + "_TransactionsExportedAt" + DateTime.Now.ToString("yyyyMMdd_HHmm");
                UID    tableUID = new UIDClass();
                tableUID.Value = "esriGeoDatabase.Feature";

                // Get the fields for this geometry type
                IFields fields = GetFields(geomType, domain);

                // Validate the fields
                ESRI.ArcGIS.Geodatabase.IFieldChecker   fieldChecker    = new ESRI.ArcGIS.Geodatabase.FieldCheckerClass();
                ESRI.ArcGIS.Geodatabase.IEnumFieldError enumFieldError  = null;
                ESRI.ArcGIS.Geodatabase.IFields         validatedFields = null;
                fieldChecker.ValidateWorkspace = ws;
                fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

                IFieldError err;
                while (enumFieldError != null && (err = enumFieldError.Next()) != null)
                {
                    // If the field validation failed, display an error (since fields are mostly hardcoded, this shouldn't really happen)
                    MessageBox.Show(Enum.GetName(typeof(esriFieldNameErrorType), err.FieldError), "Field Error");
                }

                dictionary.Add(geomType, featws.CreateFeatureClass(fcName, validatedFields, tableUID, null, esriFeatureType.esriFTSimple, "SHAPE", "DEFAULT"));
            }

            return(dictionary);
        }
Example #26
0
 private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
 {
     double xpoint = e.mapX;
     double ypoint = e.mapY;
     IPoint point = new PointClass();
     point.PutCoords(xpoint, ypoint);
     IWorkspaceFactory wsf = new FileGDBWorkspaceFactory();
     IFeatureWorkspace ws = wsf.OpenFromFile(@"\\alexn\TestGDB\Feature.gdb", 0) as IFeatureWorkspace;
     IGeoDataset pointfc = ws.OpenFeatureClass(@"Points") as IGeoDataset;
     point.SpatialReference = pointfc.SpatialReference;
     //IGeometry point2 = point as IGeometry;
     IFeatureClass pointfc2 = pointfc as IFeatureClass;
     IFeature pointfc3 = pointfc2.CreateFeature();
     IFeatureCursor pointFC = pointfc2.Insert(true);
     IFeatureBuffer fbuffer = pointfc2.CreateFeatureBuffer();
     fbuffer.Shape = point;
     pointFC.InsertFeature(fbuffer);
     IActiveView display = axMapControl1.ActiveView;
     display.Activate(0);
     display.Refresh();
 }
Example #27
0
        /// <summary>
        /// Opens the workspace of the given FGDB path.
        /// <para>If the given workspace path doesn't exist or it's an empty directory, it will be used to create the workspace and open it.</para>
        /// </summary>
        /// <param name="fgdbPath">FGDB path.</param>
        /// <returns>IWorkspace opened.</returns>
        public static IWorkspace OpenworkSpace(string fgdbPath)
        {
            if (string.IsNullOrWhiteSpace(fgdbPath))
            {
                return(null);
            }

            if (!Directory.Exists(fgdbPath) || Directory.GetFiles(fgdbPath).Length == 0)
            {
                CreateFgdbWorkspace(fgdbPath);
            }

            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();

            if (workspaceFactory.IsWorkspace(fgdbPath))
            {
                return(workspaceFactory.OpenFromFile(fgdbPath, 0));
            }

            return(null);
        }
Example #28
0
        /// <summary>
        /// 删除特定数据集下的表
        /// </summary>
        /// <param name="gdbPath">gdb路径</param>
        /// <param name="tableName">表名称</param>
        public static void DeleteFeatureClass(string gdbPath, string tableName)
        {
            IWorkspaceFactory       worFact               = new FileGDBWorkspaceFactory();
            IWorkspace              workspace             = worFact.OpenFromFile(gdbPath, 0);
            IFeatureWorkspace       featureWorkspace      = workspace as IFeatureWorkspace;
            IFeatureWorkspaceManage featureWorkspaceMange = (IFeatureWorkspaceManage)featureWorkspace;
            //得到的数据集是FeatureClass
            //IEnumDatasetName enumDatasetName = workspace.get_DatasetNames(esriDatasetType.esriDTFeatureClass);
            IEnumDatasetName enumDatasetName = workspace.get_DatasetNames(esriDatasetType.esriDTTable);
            IDatasetName     datasetName     = null;

            while ((datasetName = enumDatasetName.Next()) != null)
            {
                if (datasetName.Name.Equals(tableName))
                {
                    //删除指定要素类(表)
                    featureWorkspaceMange.DeleteByName(datasetName);
                    break;
                }
            }
        }
Example #29
0
        public static IWorkspace OpenFileGDB(string string_0)
        {
            IWorkspace        workspace = null;
            IWorkspaceFactory fileGDBWorkspaceFactoryClass = new FileGDBWorkspaceFactory();

            try
            {
                workspace = fileGDBWorkspaceFactoryClass.OpenFromFile(string_0, 0);
            }
            catch (COMException cOMException1)
            {
                COMException cOMException = cOMException1;
                int          errorCode    = cOMException.ErrorCode;
                MessageBox.Show(string.Concat("错误代码:", errorCode.ToString(), "\r\n", cOMException.Message));
            }
            catch (Exception exception)
            {
            }
            ComReleaser.ReleaseCOMObject(fileGDBWorkspaceFactoryClass);
            fileGDBWorkspaceFactoryClass = null;
            return(workspace);
        }
        //打开数据库
        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            folderBrowserDialog.ShowNewFolderButton = false;
            folderBrowserDialog.Description         = "选择.gdb文件数据库";
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                path = folderBrowserDialog.SelectedPath;
                if (path.Substring((path.Length) - 4) != ".gdb")
                {
                    MessageBox.Show("请选择*.gdb文件地理数据库!", "提示");
                    return;
                }
            }
            IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactory();

            pWorkspace    = pWorkspaceFactory.OpenFromFile(path, 0);
            FeatureDSList = getGDBFeatureDS(pWorkspace);
            foreach (IDataset pDS in FeatureDSList)
            {
                checkedListBox1.Items.Add(pDS.Name);
            }
        }
Example #31
0
        /***************************************************************************
        * 函数名:GetWorkspace
        * 参  数:无
        * 返回值:IWorkspace
        * 功  能:获取数据库参数
        ***************************************************************************/
        private IWorkspace GetWorkspace()
        {
            IWorkspace ws = null;

            try
            {
                string extension = System.IO.Path.GetExtension(GdpPath);
                if (extension == ".gdb")
                {
                    FileGDBWorkspaceFactory wsf = new FileGDBWorkspaceFactory();
                    ws = wsf.OpenFromFile(GdpPath, 0);
                }
                else if (extension == ".mdb")
                {
                    AccessWorkspaceFactory wsf = new AccessWorkspaceFactory();
                    ws = wsf.OpenFromFile(GdpPath, 0);
                }
                return(ws);
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #32
0
        /// <summary>
        /// 获取文件地理空间GDB数据库
        /// </summary>
        /// <param name="gdbPath"></param>
        /// <returns></returns>
        public static IWorkspace GetFileGDBWorkspace(string gdbPath)
        {
            if (string.IsNullOrWhiteSpace(gdbPath) || !Directory.Exists(gdbPath))
            {
                throw new Exception(string.Format("GDB文件不存在,文件路径:“{0}”", gdbPath));
            }
            else
            {
                try
                {
                    //IWorkspaceFactory pWorkspaceFac = new FileGDBWorkspaceFactory();
                    Type                    t             = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
                    System.Object           obj           = Activator.CreateInstance(t);
                    FileGDBWorkspaceFactory pWorkspaceFac = obj as FileGDBWorkspaceFactory;
                    IWorkspace              workspace     = pWorkspaceFac.OpenFromFile(gdbPath, 0);

                    return(workspace);
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("读取GDB文件失败,文件路径:“{0}”", gdbPath), ex);
                }
            }
        }
 /// <summary>
 /// Retrieves all datasets names from filegdb
 /// </summary>
 /// <param name="gdbFilePath">Path to filegdb</param>
 /// <returns>List of names of all featureclasses in filegdb</returns>
 private List<string> GetAllDatasetNames(string gdbFilePath)
 {
     IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
     IWorkspace workspace = workspaceFactory.OpenFromFile (gdbFilePath, 0);
     IEnumDataset enumDataset = workspace.get_Datasets(esriDatasetType.esriDTAny);
     List<string> names = new List<string>();
     IDataset dataset = null;
     while((dataset = enumDataset.Next())!= null)
     {
         names.Add(dataset.Name);
     }
     return names;
 }
 private IFeatureClass OpenFeatureClass(string filePath, string fcName)
 {
     var gdbWorkspaceFactory = new FileGDBWorkspaceFactory();
     var featureWorkspace = (IFeatureWorkspace)gdbWorkspaceFactory.OpenFromFile(_fgdb, 0);
     return featureWorkspace.OpenFeatureClass(fcName);
 }
        /// <summary>
        /// Creates the output featureclass, either fgdb featureclass or a shapefile
        /// </summary>
        /// <param name="outputPath">location of featureclass</param>
        /// <param name="saveAsType">Type of output selected, either fgdb featureclass or shapefile</param>
        /// <param name="graphicsList">List of graphics for selected tab</param>
        /// <param name="ipSpatialRef">Spatial Reference being used</param>
        /// <returns>Output featureclass</returns>
        public IFeatureClass CreateFCOutput(string outputPath, SaveAsType saveAsType, List<Graphic> graphicsList, ISpatialReference ipSpatialRef)
        {
            string fcName = System.IO.Path.GetFileName(outputPath);
            string folderName = System.IO.Path.GetDirectoryName(outputPath);
            IFeatureClass fc = null;

            try
            {
                if (saveAsType == SaveAsType.FileGDB)
                {
                    IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
                    IWorkspace workspace = workspaceFactory.OpenFromFile(folderName, 0);
                    IFeatureWorkspace fWorkspace = (IFeatureWorkspace)workspace;

                    if (DoesFeatureClassExist(folderName, fcName))
                    {
                        DeleteFeatureClass(fWorkspace, fcName);
                    }

                    fc = CreatePolylineFeatureClass(fWorkspace, fcName);

                    foreach (Graphic graphic in graphicsList)
                    {
                        IFeature feature = fc.CreateFeature();

                        feature.Shape = graphic.Geometry;
                        feature.Store();
                    }

                }
                else if (saveAsType == SaveAsType.Shapefile)
                {
                    // already asked them for confirmation to overwrite file
                    if (File.Exists(outputPath))
                    {
                        DeleteShapeFile(outputPath);
                    }            

                    fc = ExportToShapefile(outputPath, graphicsList, ipSpatialRef);
                }
                return fc;
            }
            catch (Exception ex)
            {
                return fc;
            }
        }
Example #36
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; }
        }
        /// <summary>
        /// 创建镶嵌数据集
        /// </summary>
        /// <param name="pFGDBPath"></param>
        /// <param name="pMDame"></param>
        /// <param name="pSrs"></param>
        /// <returns></returns>
        IMosaicDataset CreateMosaicDataset(string pFGDBPath, string pMDame, ISpatialReference pSrs )
        {
            IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactory();

                  IWorkspace pFgdbWorkspace = pWorkspaceFactory.OpenFromFile(pFGDBPath, 0);

                  ICreateMosaicDatasetParameters pCreationPars = new CreateMosaicDatasetParametersClass();

                  pCreationPars.BandCount = 3;

                  pCreationPars.PixelType = rstPixelType.PT_UCHAR;

                  IMosaicWorkspaceExtensionHelper pMosaicExentionHelper = new  MosaicWorkspaceExtensionHelperClass();

                  IMosaicWorkspaceExtension pMosaicExtention = pMosaicExentionHelper.FindExtension(pFgdbWorkspace);

                  return pMosaicExtention.CreateMosaicDataset(pMDame, pSrs, pCreationPars, "");
        }