//** 功能描述: 得到shp文件的工作空间

        public static IWorkspace CreatOrGetSHPWorkspace(string sFilePath)
        {
            IWorkspace functionReturnValue = default(IWorkspace);

            try
            {
                IWorkspaceFactory pWorkspaceFactory = default(IWorkspaceFactory);
                IWorkspace        pWorkspace        = default(IWorkspace);


                if (Microsoft.VisualBasic.FileIO.FileSystem.DirectoryExists(sFilePath) == false)
                {
                    Microsoft.VisualBasic.FileIO.FileSystem.CreateDirectory(sFilePath);
                }
                pWorkspaceFactory   = new ShapefileWorkspaceFactory();
                pWorkspace          = pWorkspaceFactory.OpenFromFile(sFilePath, 0);
                functionReturnValue = pWorkspace;
                return(functionReturnValue);
            }
            catch
            {
                functionReturnValue = null;
                return(functionReturnValue);
            }
        }
示例#2
0
        public IFeatureClass GetFeatureClass(string inFileName)
        {
            string        path     = string.Empty;
            string        fileName = string.Empty;
            IFeatureClass ifc      = null;

            try
            {
                this.GetPathAndFileName(inFileName, out path, out fileName);
                IWorkspaceFactory wrkSpaceFactory  = new ShapefileWorkspaceFactory();
                IFeatureWorkspace featureWorkspace = null;
                featureWorkspace = (IFeatureWorkspace)wrkSpaceFactory.OpenFromFile(path, 0);
                ifc = featureWorkspace.OpenFeatureClass(fileName);
            }
            catch (COMException COMEx)
            {
                eLog.Debug(COMEx);
                eLog.Debug("Orginal File Name was " + inFileName);
                eLog.Debug("so the path is  " + path);
                eLog.Debug("just the file name is" + fileName);
                //System.Windows.Forms.MessageBox.Show(COMEx.GetBaseException().ToString(), "COM Error: " + COMEx.ErrorCode.ToString());
            }

            catch (System.Exception ex)
            {
                eLog.Debug(ex);
                //System.Windows.Forms.MessageBox.Show(ex.Source + " ");//+ ex.InnerException.ToString());
            }

            return(ifc);
        }
示例#3
0
        private void UpdateSpatialInfoElements(string strSPInfo)
        {
            string strTableName    = txtFlowFile.Text;
            string strSourceFolder = null;
            string strSourceFile   = null;

            if (strTableName == "")
            {
                return;
            }
            else
            {
                strSourceFolder = System.IO.Path.GetDirectoryName(strTableName);
                strSourceFile   = System.IO.Path.GetFileName(strTableName);
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
                IWorkspace        ws  = workspaceFactory.OpenFromFile(strSourceFolder, 0);
                IFeatureWorkspace fws = ws as IFeatureWorkspace;

                m_tblFlow = fws.OpenTable(strSourceFile);

                IFields fields = m_tblFlow.Fields;

                if (strSPInfo == "From ShapeFile")
                {
                    cbo1.Items.Clear();
                    cbo2.Items.Clear();
                    cbo3.Items.Clear();
                    cbo4.Items.Clear();

                    for (int i = 0; i < m_pForm.axMapControl1.LayerCount; i++)
                    {
                        cbo1.Items.Add(m_pForm.axMapControl1.get_Layer(i).Name);
                    }

                    for (int i = 0; i < fields.FieldCount; i++)
                    {
                        cbo3.Items.Add(fields.get_Field(i).Name);
                        cbo4.Items.Add(fields.get_Field(i).Name);
                    }
                }
                else if (strSPInfo == "From Table")
                {
                    cbo1.Items.Clear();
                    cbo2.Items.Clear();
                    cbo3.Items.Clear();
                    cbo4.Items.Clear();

                    for (int i = 0; i < fields.FieldCount; i++)
                    {
                        if (m_pSnippet.FindNumberFieldType(fields.get_Field(i)))
                        {
                            cbo1.Items.Add(fields.get_Field(i).Name);
                            cbo2.Items.Add(fields.get_Field(i).Name);
                            cbo3.Items.Add(fields.get_Field(i).Name);
                            cbo4.Items.Add(fields.get_Field(i).Name);
                        }
                    }
                }
            }
        }
示例#4
0
        /// <summary>
        /// 作用:打开shapefile文件 并获取workspace
        /// 作者:汪建龙
        /// 编写时间:2017年4月11日15:37:02
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static IWorkspace OpenShapefileWorkSpace(string filePath)
        {
            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(filePath, 0);

            return(workspace);
        }
        public List <ILayer> ReadShapLayer(List <string> filePathList)
        {
            List <ILayer> layerList = new List <ILayer>();

            if (filePathList.Count == 0)
            {
                return(null);
            }
            else
            {
                foreach (string path in filePathList)
                {
                    IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
                    IWorkspace        pWorkspace        = pWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(path), 0);
                    IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;

                    IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(path));
                    IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                    pFeatureLayer.FeatureClass = pFeatureClass;
                    pFeatureLayer.Name         = System.IO.Path.GetFileNameWithoutExtension(path);
                    layerList.Add(pFeatureLayer as ILayer);
                }
                return(layerList);
            }
        }
示例#6
0
        /// <summary>
        /// 打开shapefile文件
        /// </summary>
        private void btnOpenShapfile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dg = new OpenFileDialog();

            dg.Filter      = "Shapefile文件(.shp)|*.shp";
            dg.Multiselect = true;
            if (dg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string fileName = dg.FileName;
                if (string.IsNullOrEmpty(fileName))
                {
                    MessageBox.Show("请选择要打开的shapefile文件");
                    return;
                }

                IWorkspaceFactory pWksFactory = new ShapefileWorkspaceFactory();
                IWorkspace        pWks        = pWksFactory.OpenFromFile(System.IO.Path.GetDirectoryName(fileName), 0);
                IFeatureWorkspace pFeatureWks = (IFeatureWorkspace)pWks;
                IFeatureClass     pFc         = pFeatureWks.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(fileName));
                IFeatureLayer     pFlayer     = new FeatureLayerClass();
                pFlayer.FeatureClass = pFc;
                pFlayer.Name         = pFc.AliasName;
                this.axMapControl1.Map.AddLayer((ILayer)pFlayer);
                this.axMapControl1.ActiveView.Extent = this.axMapControl1.ActiveView.FullExtent;
                this.axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }
        }
示例#7
0
        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenFileDialog openDLG = new OpenFileDialog();                                           //创建打开文件对话框

            openDLG.Title  = "open Shape File";                                                      //  给对话框的标题赋值
            openDLG.Filter = "Shape File(*.shp)|*.shp";                                              // 设定对话框可以打开的文件类型,文件后缀为*.shp
            if (openDLG.ShowDialog() == DialogResult.OK)                                             // 打开对话框,若对话框操作选择文件完成后选择的是ok按钮,则执行下面的代码
            {
                string sFilePath = openDLG.FileName;                                                 //   获取选择的文件的路径和名称
                int    index     = sFilePath.LastIndexOf("\\");                                      // 判定文件名字符串中的最后一个“\”符号的位置

                string            sPath             = sFilePath.Substring(0, index);                 //截取文件路径
                string            sFileName         = sFilePath.Substring(index + 1);                //截取文件名称
                IWorkspaceFactory pWorkspaceFectory = new ShapefileWorkspaceFactory();               //创建能打开shapefile数据文件的工作空间工厂对象
                IWorkspace        pWorkspace        = pWorkspaceFectory.OpenFromFile(sPath, 0);      // 用工作空间工厂对象将shapefile文件所在的文件夹打开,作为工作空间对象
                IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;               // 将工作空间接口转换为 矢量特征工作空间接口
                IFeatureClass     pFeatureClass     = pFeatureWorkspace.OpenFeatureClass(sFileName); // 调用矢量特征工作空间接口的OpenFeatureClass方法打开shapefile矢量特征类,矢量特征类中存放的就是矢量数据
                ILayer            pLayer            = new FeatureLayer();                            // 创建一个矢量特征层
                IFeatureLayer     pFeatureLayer     = pLayer as IFeatureLayer;                       // 获得矢量特征层接口对象
                pFeatureLayer.FeatureClass = pFeatureClass;                                          //将矢量特征层的数据源指向刚打开的shapefile矢量特征类
                axMapControl1.Map.AddLayer(pLayer);                                                  //将矢量特征层添加到地图控件的地图中
                axMapControl1.ActiveView.Refresh();                                                  //刷新地图
            }
            //添加shape数据
        }
        private void OutputTxt(string shpfile, string txtPath)
        {
            FileInfo finfo     = new FileInfo(shpfile);
            string   parFolder = System.IO.Path.GetDirectoryName(shpfile);

            if (!Directory.Exists(parFolder))
            {
                Directory.CreateDirectory(parFolder);
            }
            IWorkspaceFactory shpwf        = new ShapefileWorkspaceFactory();
            IFeatureWorkspace featureWs    = shpwf.OpenFromFile(parFolder, 0) as IFeatureWorkspace;
            IFeatureClass     featureclass = featureWs.OpenFeatureClass(finfo.Name);
            IFeatureCursor    cursor       = featureclass.Search(null, false);
            IFeature          pfeat        = cursor.NextFeature();
            StringBuilder     sb           = new StringBuilder();

            sb.Append("ID,x,y,z\r\n");
            int index = 1;

            while (pfeat != null)
            {
                IPoint pt = pfeat.Shape as IPoint;
                sb.Append(string.Format("{0},{1},{2},{3}\r\n", index++, pt.X, pt.Y, pt.Z));
                pfeat = cursor.NextFeature();
            }
            ComReleaser.ReleaseCOMObject(cursor);
            ComReleaser.ReleaseCOMObject(pfeat);
            ComReleaser.ReleaseCOMObject(featureclass);
            ComReleaser.ReleaseCOMObject(shpwf);
            File.WriteAllText(txtPath, sb.ToString(), Encoding.Default);
        }
示例#9
0
文件: Form1.cs 项目: eglrp/Excercise
        private void btn_open_Click(object sender, EventArgs e)
        {
            OpenFileDialog xjOpenShpFileDialog = new OpenFileDialog();

            xjOpenShpFileDialog.Title  = "打开矢量数据";
            xjOpenShpFileDialog.Filter = "矢量文件(*.shp)|*.shp";


            if (xjOpenShpFileDialog.ShowDialog() == DialogResult.OK)
            {
                string xjShpPath     = xjOpenShpFileDialog.FileName;
                string xjShpFolder   = System.IO.Path.GetDirectoryName(xjShpPath);
                string xjShpFileName = System.IO.Path.GetFileName(xjShpPath);
                //工作工厂+工作空间
                IWorkspaceFactory xjShpWsF = new ShapefileWorkspaceFactory();
                IFeatureWorkspace xjShpFWs = (IFeatureWorkspace)xjShpWsF.OpenFromFile(xjShpFolder, 0);
                //新建矢量图层:要素+名称
                IWorkspace    xjShpWs           = xjShpWsF.OpenFromFile(xjShpFolder, 0);
                IFeatureClass xjShpFeatureClass = xjShpFWs.OpenFeatureClass(xjShpFileName);
                IFeatureLayer xjShpFeatureLayer = new FeatureLayer();
                xjShpFeatureLayer.FeatureClass = xjShpFeatureClass;
                xjShpFeatureLayer.Name         = xjShpFeatureClass.AliasName;
                //加载刷新
                this.axMapControl1.AddLayer(xjShpFeatureLayer);
                this.axMapControl1.ActiveView.Refresh();
            }

            IPoint p = new ESRI.ArcGIS.Geometry.Point();
        }
示例#10
0
        private IFeatureClass CreateShapeFile(string shapeFullname, string proj)
        {
            FileInfo finfo     = new FileInfo(shapeFullname);
            string   parFolder = System.IO.Path.GetDirectoryName(shapeFullname);

            if (!Directory.Exists(parFolder))
            {
                Directory.CreateDirectory(parFolder);
            }
            IWorkspaceFactory shpwf       = new ShapefileWorkspaceFactory();
            IFeatureWorkspace featureWs   = shpwf.OpenFromFile(parFolder, 0) as IFeatureWorkspace;
            IFields           pFields     = new FieldsClass();
            IFieldsEdit       pFieldsEdit = pFields as IFieldsEdit;

            //添加几何字段
            IField     pField     = new FieldClass();
            IFieldEdit pFieldEdit = pField as IFieldEdit;

            pFieldEdit.Name_2 = "Shape";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

            IGeometryDef     pGeomDef     = new GeometryDefClass();
            IGeometryDefEdit pGeomDefEdit = pGeomDef as IGeometryDefEdit;

            pGeomDefEdit.GeometryType_2     = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint; //几何类型
            pGeomDefEdit.HasZ_2             = true;                                                    //是否有Z值
            pGeomDefEdit.SpatialReference_2 = CreateSpatialReference(proj);                            //设置空间参考
            pFieldEdit.GeometryDef_2        = pGeomDef;
            pFieldsEdit.AddField(pField);
            return(featureWs.CreateFeatureClass(finfo.Name, pFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", null));
        }
        //<CSCM>
        //********************************************************************************
        //** 函 数 名: CreatOrGetSHPWorkspace
        //** 版    权: CopyRight (C)
        //** 创 建 人: 杨旭斌
        //** 功能描述: 得到shp文件的工作空间
        //** 创建日期:
        //** 修 改 人:
        //** 修改日期:
        //** 修改时间: 20070818
        //** 参数列表: sFilePath (String)
        //** 版    本:1.0
        //*********************************************************************************
        //</CSCM>
        public static IWorkspace CreatOrGetSHPWorkspace(string sFilePath)
        {
            IWorkspace        functionReturnValue = default(IWorkspace);
            IWorkspaceFactory pWorkspaceFactory   = default(IWorkspaceFactory);
            IWorkspace        pWorkspace          = default(IWorkspace);

            // ERROR: Not supported in C#: OnErrorStatement


            //'如果shapefile文件夹存在,则删除整个文件夹,再重建一个空文件夹  3/10/2009 yh
            //If FileSystem.DirectoryExists(sFilePath) Then
            //    FileSystem.DeleteDirectory(sFilePath, DeleteDirectoryOption.DeleteAllContents)
            //    FileSystem.CreateDirectory(sFilePath)
            //Else
            //    FileSystem.CreateDirectory(sFilePath)
            //End If

            if (Directory.Exists(sFilePath) == false)
            {
                Directory.CreateDirectory(sFilePath);
                //Microsoft.VisualBasic.FileIO.FileSystem.CreateDirectory(sFilePath);
            }
            pWorkspaceFactory   = new ShapefileWorkspaceFactory();
            pWorkspace          = pWorkspaceFactory.OpenFromFile(sFilePath, 0);
            functionReturnValue = pWorkspace;
            return(functionReturnValue);

Err_GetSHPWorkspace:
            functionReturnValue = null;
            return(functionReturnValue);
        }
示例#12
0
        /// <summary>
        /// 加载.shp文件
        /// </summary>
        /// <param name="fileName"></param>
        private void OpenShpFile(string fileName)
        {
            try
            {
                string            path              = fileName;
                string            pFolder           = System.IO.Path.GetDirectoryName(path);
                string            pFileName         = System.IO.Path.GetFileName(path);
                IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
                IWorkspace        pWorkspace        = pWorkspaceFactory.OpenFromFile(pFolder, 0);
                IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
                IFeatureClass     featureClass      = pFeatureWorkspace.OpenFeatureClass(pFileName);
                //创建layer并把上一步生成的featureClass赋值给featureLayer
                IFeatureLayer featureLayer = new FeatureLayerClass();
                featureLayer.FeatureClass = featureClass;
                featureLayer.Name         = featureClass.AliasName;
                IGroupLayer groupLayer = new GroupLayerClass();
                groupLayer.Name = "add" + pFileName;
                groupLayer.Add(featureLayer);

                axGlobeControl.Globe.AddLayerType(groupLayer as ILayer, esriGlobeLayerType.esriGlobeLayerTypeElevation, true);
            }
            catch (Exception)
            {
            }
        }
示例#13
0
        /// <summary>
        /// 添加shp文件
        /// </summary>
        /// <param name="mapControl">要添加文件的地图控件</param>
        public void AddShpFile(AxMapControl mapControl)
        {
            //获取文件路径
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Title            = "加载shp文件";
            openFileDialog.Filter           = "矢量文件(*.shp)|*.shp";
            openFileDialog.Multiselect      = false;
            openFileDialog.RestoreDirectory = false;
            openFileDialog.CheckFileExists  = true;
            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            //文件路径和文件名
            string fullPath = openFileDialog.FileName;
            int    subIndex = fullPath.LastIndexOf("\\");
            string filePath = fullPath.Substring(0, subIndex);
            string fileName = fullPath.Substring(subIndex + 1);
            //获取数据集
            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, 0);
            IFeatureLayer     featureLayer     = new FeatureLayer();

            featureLayer.FeatureClass = featureWorkspace.OpenFeatureClass(fileName);
            featureLayer.Name         = featureLayer.FeatureClass.AliasName;
            //添加数据
            mapControl.Map.AddLayer(featureLayer);
            mapControl.ActiveView.Refresh();

            //mapControl.AddShapeFile(filePath, fileName);    //控件自带的方法
        }
示例#14
0
        public IWorkspace OpenLoaclGeoDataBase(string path, EnumLoaclGeoDatabaseType type)
        {
            try
            {
                IWorkspaceFactory pTargetWsf = null;
                switch (type)
                {
                case EnumLoaclGeoDatabaseType.MDB:
                    pTargetWsf = new AccessWorkspaceFactory();
                    break;

                case EnumLoaclGeoDatabaseType.GDB:
                    pTargetWsf = new FileGDBWorkspaceFactory();
                    break;

                case EnumLoaclGeoDatabaseType.SHP:
                    pTargetWsf = new ShapefileWorkspaceFactory();
                    break;
                }
                return(pTargetWsf.OpenFromFile(path, 0));
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                return(null);
            }
        }
示例#15
0
            //注册要素类
            /// <summary>
            /// 返回true说明FeatureClass存在,返回false说明不存在,重新创建
            /// </summary>
            /// <param name="IN_ShapePath"></param>
            /// <returns></returns>
            private bool PRV_AddFeatureClass(string IN_ShapePath)
            {
                string            Temp_Direction         = System.IO.Path.GetDirectoryName(IN_ShapePath);            //该Shp文件的目录
                string            Temp_Name              = System.IO.Path.GetFileNameWithoutExtension(IN_ShapePath); //该Shp文件的名称
                IWorkspaceFactory Temp_ShapeWorkFactory  = new ShapefileWorkspaceFactory();
                IFeatureWorkspace Temp_ShapeWorkspace    = Temp_ShapeWorkFactory.OpenFromFile(Temp_Direction, 0) as IFeatureWorkspace;
                IWorkspaceFactory Temp_AccessWorkFactory = new AccessWorkspaceFactory();
                IFeatureWorkspace Temp_Workspace         = Temp_AccessWorkFactory.OpenFromFile(S_MDBFile, 0) as IFeatureWorkspace;

                IFeatureClassContainer tem_FeatureClassContainer = (IFeatureClassContainer)FDS_Featuredataset;
                IEnumFeatureClass      pEnumFeatureClass         = (IEnumFeatureClass)tem_FeatureClassContainer.Classes;
                IFeatureClass          tem_FeatureClass          = pEnumFeatureClass.Next();

                while (null != tem_FeatureClass)
                {
                    if (Temp_Name == tem_FeatureClass.AliasName)
                    {// return true;
                    }
                    tem_FeatureClass = pEnumFeatureClass.Next();
                }

                IFeatureClass Temp_FeatureClass        = Temp_ShapeWorkspace.OpenFeatureClass(Temp_Name);
                FeatureClassToFeatureClass Temp_FCToFC = new FeatureClassToFeatureClass(IN_ShapePath, S_MDBFile + "\\" + FDS_Featuredataset.Name, Temp_Name);//将Shp文件导入要素数据集

                GP_Progress = GP_Tool.ExecuteAsync(Temp_FCToFC);
                TH_TimeSpan = new Thread(PRV_GetStatus);//开辟线程计时
                TH_TimeSpan.Start();
                TH_TimeSpan.Join();

                return(false);
                // IFeatureClassContainer ss = (FDS_Featuredataset.Workspace as IFeatureWorkspace).OpenFeatureDataset(FDS_Featuredataset.Name) as IFeatureClassContainer;
                //  Console.WriteLine("完成");
            }
示例#16
0
        public IFeatureClass getShapeFile(string fileName)
        {
            IFeatureClass ifc = null;

            try
            {
                IWorkspaceFactory wrkSpaceFactory  = new ShapefileWorkspaceFactory();
                IFeatureWorkspace featureWorkspace = null;
                featureWorkspace = (IFeatureWorkspace)wrkSpaceFactory.OpenFromFile(this.myPath, 0);
                ifc = featureWorkspace.OpenFeatureClass(fileName);
            }
            catch (COMException COMEx)
            {
                System.Windows.Forms.MessageBox.Show(COMEx.GetBaseException().ToString(), "COM Error: " + COMEx.ErrorCode.ToString());
                eLog.Debug(COMEx.Source);
            }

            catch (System.Exception ex)
            {
#if (DEBUG)
                //System.Windows.Forms.MessageBox.Show (ex.Source + " " );//+ ex.InnerException.ToString());
#endif
                eLog.Debug(ex.Source);
            }

            return(ifc);
        }
        //添加导入的要素类
        private void button5_Click(object sender, EventArgs e)
        {
            int               index;
            string            path, name;
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace        pWorkspace2;
            IFeatureWorkspace pFeatureWorkspace;
            OpenFileDialog    openFileDialog = new OpenFileDialog();

            openFileDialog.Title       = "选择要添加的要素类";
            openFileDialog.Multiselect = true;
            openFileDialog.Filter      = "shp文件(*.shp)|*.shp";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                List <string> FileList = new List <string>();
                foreach (string s in openFileDialog.FileNames)
                {
                    listBox1.Items.Add(s);
                    index             = s.LastIndexOf("\\");
                    path              = s.Substring(0, index);
                    name              = s.Substring(index + 1);
                    pWorkspace2       = pWorkspaceFactory.OpenFromFile(path, 0);
                    pFeatureWorkspace = pWorkspace2 as IFeatureWorkspace;
                    pFeatureClassList.Add(pFeatureWorkspace.OpenFeatureClass(name));
                }
            }
        }
示例#18
0
        public static IFeatureLayer OpenShapefile(ref string shapefilePath)
        {
            OpenFileDialog dg = new OpenFileDialog();

            dg.Filter      = "Shapefile文件(.shp)|*.shp";
            dg.Multiselect = true;
            if (dg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string fileName = dg.FileName;
                shapefilePath = fileName;
                if (string.IsNullOrEmpty(fileName))
                {
                    MessageBox.Show("请选择要打开的shapefile文件");
                    return(null);
                }

                IWorkspaceFactory pWksFactory = new ShapefileWorkspaceFactory();
                IWorkspace        pWks        = pWksFactory.OpenFromFile(System.IO.Path.GetDirectoryName(fileName), 0);
                IFeatureWorkspace pFeatureWks = (IFeatureWorkspace)pWks;
                IFeatureClass     pFc         = pFeatureWks.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(fileName));
                IFeatureLayer     pFlayer     = new FeatureLayerClass();
                pFlayer.FeatureClass = pFc;
                pFlayer.Name         = pFc.AliasName;
                return(pFlayer);
            }
            return(null);
        }
示例#19
0
        public static IFeatureWorkspace CreateFeatureWorkspace(string shapefilePath)
        {
            IWorkspaceFactory pWksFactory = new ShapefileWorkspaceFactory();
            IWorkspace        pWks        = pWksFactory.OpenFromFile(System.IO.Path.GetDirectoryName(shapefilePath), 0);
            IFeatureWorkspace pFeatureWks = pWks as IFeatureWorkspace;

            return(pFeatureWks);
        }
示例#20
0
        protected IFeatureClass OpenShapefile(string path, string Name, int hWnd)
        {
            IFeatureWorkspace pFWS;
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();

            pFWS = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(path, hWnd);     //, Application.hWnd);
            return(pFWS.OpenFeatureClass(Name));
        }
示例#21
0
文件: LoadHelper.cs 项目: jzChia/demo
        public static string GetNameShapeFile(string gdb_Path, string file_Name)
        {
            IWorkspaceFactory wsf = new ShapefileWorkspaceFactory();
            IWorkspace        ws  = wsf.OpenFromFile(gdb_Path, 0);
            IEnumDatasetName  edn = ws.get_DatasetNames(esriDatasetType.esriDTFeatureClass);

            return(Check(edn, file_Name, string.Empty));
        }
示例#22
0
        public static void Mlayer_IDW_Click()
        {
            // 用反距离IDW插值生成的栅格图像。如下:
            IInterpolationOp pInterpolationOp = new RasterInterpolationOpClass();

            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
            string            pPath             = Application.StartupPath + @"\MakeContours\Cont.shp";
            string            pFolder           = System.IO.Path.GetDirectoryName(pPath);
            string            pFileName         = System.IO.Path.GetFileName(pPath);

            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(pFolder, 0);

            IFeatureWorkspace       pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
            IFeatureClass           oFeatureClass     = pFeatureWorkspace.OpenFeatureClass(pFileName);
            IFeatureClassDescriptor pFCDescriptor     = new FeatureClassDescriptorClass();

            pFCDescriptor.Create(oFeatureClass, null, "shape.z");
            IRasterRadius pRadius = new RasterRadiusClass();

            object objectMaxDistance = null;
            object objectbarrier     = null;
            object missing           = Type.Missing;

            pRadius.SetVariable(12, ref objectMaxDistance);

            object    dCellSize      = 1;
            object    snapRasterData = Type.Missing;
            IEnvelope pExtent;

            pExtent = new EnvelopeClass();
            Double xmin = 27202;
            Double xmax = 31550;

            Double ymin = 19104;
            Double ymax = 22947;

            pExtent.PutCoords(xmin, ymin, xmax, ymax);
            object extentProvider           = pExtent;
            IRasterAnalysisEnvironment pEnv = pInterpolationOp as IRasterAnalysisEnvironment;

            pEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dCellSize);
            pEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData);
            IGeoDataset poutGeoDataset = pInterpolationOp.IDW((IGeoDataset)pFCDescriptor, 2, pRadius, ref objectbarrier);
            ISurfaceOp  surOp          = new RasterSurfaceOpClass();


            IRaster pOutRaster = poutGeoDataset as IRaster;

            IRasterLayer pOutRasLayer = new RasterLayer();

            pOutRasLayer.CreateFromRaster(pOutRaster);

            IMap pMap = Common.DataEditCommon.g_pMap;

            pMap.AddLayer(pOutRasLayer);
            Common.DataEditCommon.g_axTocControl.Refresh();
            Common.DataEditCommon.g_pAxMapControl.ActiveView.Refresh();
        }
示例#23
0
        protected bool ShowSaveFileDialog(IGxDialog pGxDialog, out string path, out string name, out string genericName, out string datasetType)
        {
            path            = ""; name = ""; genericName = ""; datasetType = "";
            pGxDialog.Title = "Save File as:";
            if (!pGxDialog.DoModalSave(0))
            {
                return(false);
            }

            datasetType = pGxDialog.ObjectFilter.Name;

            //    ' delete the existing shapefile if user wants to replace it.
            if (pGxDialog.ReplacingObject)
            {
                switch (datasetType)
                {
                case "Shapefiles":
                    IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
                    IFeatureWorkspace pFWS       = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(pGxDialog.FinalLocation.FullName, 0);//        mFile(pGxDialullName, 0)
                    IFeatureClass     pFeatClass = pFWS.OpenFeatureClass(pGxDialog.Name);
                    if (!DeleteShapefile(pFeatClass))
                    {
                        MessageBox.Show("Please specify a different name for the output shapefile", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return(false);
                    }
                    break;
                }
            }

            if (!(pGxDialog.Name.IndexOf(".") == 0))
            {
                genericName = pGxDialog.Name;
            }
            else
            {
                genericName = pGxDialog.Name.Substring(0, pGxDialog.Name.IndexOf("."));
            }

            //if (sTelNo.IndexOf('/') >= 0)
            //{
            //    sTelNo = sTelNo.Substring(0, sTelNo.IndexOf('/'));
            //}
            switch (datasetType)
            {
            case "Shapefiles":
                name = genericName + ".shp";
                break;

            case "Raster Datasets":
                name = genericName + ".img";
                break;
            }

            path = pGxDialog.FinalLocation.FullName;

            return(true);
        }
示例#24
0
文件: Form1.cs 项目: adsort/mfeditor
        private void button1_Click(object sender, EventArgs e)
        {
            IWorkspaceFactory pWsf = new ShapefileWorkspaceFactory();
            IWorkspace pWs = pWsf.OpenFromFile("",0);
            IFeatureWorkspace pFws = pWs as IFeatureWorkspace;
            IFeatureClass pFc = pFws.OpenFeatureClass("");

            //pWs = new WorkspaceClass();
        }
示例#25
0
        public static void Mlayer_Krige_Click()
        {
            // 用克里金Krige插值生成的栅格图像。如下:
            IWorkspaceFactory       pWorkspaceFactory = new ShapefileWorkspaceFactory();
            string                  pPath             = Application.StartupPath + @"\MakeContours\Cont.shp";
            string                  pFolder           = System.IO.Path.GetDirectoryName(pPath);
            string                  pFileName         = System.IO.Path.GetFileName(pPath);
            IWorkspace              pWorkspace        = pWorkspaceFactory.OpenFromFile(pFolder, 0);
            IFeatureWorkspace       pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
            IFeatureClass           oFeatureClass     = pFeatureWorkspace.OpenFeatureClass(pFileName);
            IFeatureClassDescriptor pFCDescriptor     = new FeatureClassDescriptorClass();

            pFCDescriptor.Create(oFeatureClass, null, "shape.z");

            IInterpolationOp           pInterpolationOp = new RasterInterpolationOpClass();
            IRasterAnalysisEnvironment pEnv             = pInterpolationOp as IRasterAnalysisEnvironment;

            object Cellsize = 0.004;//Cell size for output raster;0.004

            pEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref Cellsize);
            //设置输出范围
            //27202 19104;27202 22947;31550 22947;31550 19104
            object    snapRasterData = Type.Missing;
            IEnvelope pExtent;

            pExtent = new EnvelopeClass();
            Double xmin = 27202;
            Double xmax = 31550;

            Double ymin = 19104;
            Double ymax = 22947;

            pExtent.PutCoords(xmin, ymin, xmax, ymax);
            object extentProvider = pExtent;

            pEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData);
            Double        dSearchD     = 10;
            object        pSearchCount = 3;
            object        missing      = Type.Missing;
            IRasterRadius pRadius      = new RasterRadius();

            pRadius.SetFixed(dSearchD, ref pSearchCount);
            //pRadius.SetVariable((int)pSearchCount, ref dSearchD);

            IGeoDataset poutGeoDataset = pInterpolationOp.Krige((IGeoDataset)pFCDescriptor, esriGeoAnalysisSemiVariogramEnum.esriGeoAnalysisGaussianSemiVariogram, pRadius, false, ref missing);

            IRaster      pOutRaster   = poutGeoDataset as IRaster;
            IRasterLayer pOutRasLayer = new RasterLayer();

            pOutRasLayer.CreateFromRaster(pOutRaster);

            IMap pMap = Common.DataEditCommon.g_pMap;

            pMap.AddLayer(pOutRasLayer);
            Common.DataEditCommon.g_axTocControl.Refresh();
            Common.DataEditCommon.g_pAxMapControl.ActiveView.Refresh();
        }
示例#26
0
        private static void DeleteShpFile(string pathName, string fileName)
        {
            IWorkspaceFactory pWSF            = new ShapefileWorkspaceFactory();
            IFeatureWorkspace pFWS            = pWSF.OpenFromFile(pathName, 0) as IFeatureWorkspace;
            IFeatureClass     pFeatureClass   = pFWS.OpenFeatureClass(fileName);
            IDataset          pFeatureDataset = pFeatureClass as IDataset;

            pFeatureDataset.Delete();
        }
示例#27
0
        //编写读取shapefile数据的方法:
        public IFeatureClass OpenShapeFeatureClass(string shpPath, string shpName)
        {
            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(shpPath, 0); //调用工厂的方法;
            IFeatureWorkspace shpWorkspace     = (IFeatureWorkspace)workspace;              //强制转换接口;
            IFeatureClass     featureClass     = shpWorkspace.OpenFeatureClass(shpName);    //声明一个要素类对象,调用工作空间的方法打开要素并赋值,传入参数为文件名

            return(featureClass);
        }
示例#28
0
        public void Test()
        {
            //定义一个几何字段,类型为点类型
            ISpatialReferenceFactory2 originalSpatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference         originalSpatialReference        = originalSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
            IGeometryDefEdit          pGeoDef     = new GeometryDefClass();
            IGeometryDefEdit          pGeoDefEdit = pGeoDef as IGeometryDefEdit;

            pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;

            pGeoDefEdit.SpatialReference_2 = originalSpatialReference;
            //定义一个字段集合对象
            IFields     pFields     = new FieldsClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;

            //定义shape字段
            IField     pField     = new FieldClass();
            IFieldEdit pFieldEdit = (IFieldEdit)pField;

            pFieldEdit.Name_2 = "SHAPE";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            pFieldsEdit.AddField(pField);
            pFieldEdit.GeometryDef_2 = pGeoDef;

            //定义单个的字段,并添加到字段集合中
            pField            = new FieldClass();
            pFieldEdit        = (IFieldEdit)pField;
            pFieldEdit.Name_2 = "STCD";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            pFieldsEdit.AddField(pField);

            //定义单个的字段,并添加到字段集合中
            pField            = new FieldClass();
            pFieldEdit        = (IFieldEdit)pField;
            pFieldEdit.Name_2 = "SLM10";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            pFieldsEdit.AddField(pField);

            //定义单个的字段,并添加到字段集合中
            pField            = new FieldClass();
            pFieldEdit        = (IFieldEdit)pField;
            pFieldEdit.Name_2 = "SLM20";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            pFieldsEdit.AddField(pField);

            //定义单个的字段,并添加到字段集合中
            pField            = new FieldClass();
            pFieldEdit        = (IFieldEdit)pField;
            pFieldEdit.Name_2 = "SLM40";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            pFieldsEdit.AddField(pField);

            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
            IFeatureWorkspace pFWS     = pWorkspaceFactory.OpenFromFile(workspaceDirectory, 0) as IFeatureWorkspace;
            IFeatureClass     pFtClass = pFWS.CreateFeatureClass("Test", pFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", null);
        }
示例#29
0
        protected override void OnClick()
        {
            //
            //  TODO: Sample code showing how to access button host
            //

            var referenceFactory2             = (ISpatialReferenceFactory2) new SpatialReferenceEnvironment();
            ISpatialReference WGS84           = referenceFactory2.CreateSpatialReference((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
            IPointCollection  pointCollection = new PolylineClass();

            // ------------- Ensure that both points have negative longitude values -------------------
            IPoint point = new PointClass();

            point.PutCoords(-170, 10); // Equivalent to 170 degrees WEST
            point.SpatialReference = WGS84;
            pointCollection.AddPoint(point);


            point = new PointClass();
            point.PutCoords(-200, 10); // Equivalent to 160 degrees EAST
            point.SpatialReference = WGS84;
            pointCollection.AddPoint(point);
            // -----------------------------------------------------------------------

            IPolyline polyline = (IPolyline)pointCollection;

            polyline.SpatialReference = WGS84;

            var geometryDefEdit = (IGeometryDefEdit) new GeometryDef();

            geometryDefEdit.GeometryType_2     = esriGeometryType.esriGeometryPolyline;
            geometryDefEdit.SpatialReference_2 = WGS84;

            var field = (IFieldEdit) new Field();

            field.Name_2        = "Shape";
            field.Type_2        = esriFieldType.esriFieldTypeGeometry;
            field.GeometryDef_2 = geometryDefEdit;

            var fields = (IFieldsEdit) new Fields();

            fields.AddField(field);

            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
            var           featureWorkspace     = (IFeatureWorkspace)workspaceFactory.OpenFromFile("C:\\Temp\\", 0);
            IFeatureClass featureClass         = featureWorkspace.CreateFeatureClass
                                                     ("test3.shp", fields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

            var feature = featureClass.CreateFeature();

            feature.Shape = polyline;
            feature.Store();


            ArcMap.Application.CurrentTool = null;
        }
示例#30
0
        private void btnSHP_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();

            openFile.Filter      = "*.shp|*.shp";
            openFile.Title       = "选择shp文件";
            openFile.Multiselect = true;

            ESRI.ArcGIS.Geometry.ISpatialReference pSpa = null;

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                string[] strs = openFile.FileNames;
                this.lstLyrFile.Items.Clear();
                for (int i = 0; i < strs.GetLength(0); i++)
                {
                    string str = strs[i];
                    this.lstLyrFile.Items.Add(System.IO.Path.GetFileNameWithoutExtension(str));

                    //获得一个源数据的空间参考
                    //获得空间参看 源的

                    if (pSpa == null)
                    {
                        IWorkspaceFactory pFac = new ShapefileWorkspaceFactory();
                        IWorkspace        pWks = pFac.OpenFromFile(System.IO.Path.GetDirectoryName(str), 0);
                        if (pWks == null)
                        {
                            continue;
                        }
                        IFeatureWorkspace pFeaWks = pWks as IFeatureWorkspace;
                        IFeatureClass     pFeaCls = pFeaWks.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(str));
                        if (pFeaCls == null)
                        {
                            continue;
                        }
                        IGeoDataset pGeoData = pFeaCls as IGeoDataset;

                        pSpa = pGeoData.SpatialReference;
                        if (pSpa == null)
                        {
                            continue;
                        }
                        m_strInPrj = ExportToESRISpatialReference(pSpa);
                        pFeaWks    = null;
                    }
                }

                for (int i = 0; i < this.lstLyrFile.Items.Count; i++)
                {
                    this.lstLyrFile.Items[i].Checked = true;
                }

                this.txtSource.Text = System.IO.Path.GetDirectoryName(strs[0]);
            }
        }
示例#31
0
        private IFeatureClass openShapefile(string pFilePath, string pFileName)
        {
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace        pWorkspace        = pWorkspaceFactory.OpenFromFile(pFilePath, 0);
            IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace;
            IFeatureClass     pFeatureClass;

            pFeatureClass = pFeatureWorkspace.OpenFeatureClass(pFileName);
            return(pFeatureClass);
        }
示例#32
0
        protected override void OnClick()
        {
            //
            //  TODO: Sample code showing how to access button host
            //

            var referenceFactory2 = (ISpatialReferenceFactory2)new SpatialReferenceEnvironment();
            ISpatialReference WGS84 = referenceFactory2.CreateSpatialReference((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
            IPointCollection pointCollection = new PolylineClass();

            // ------------- Ensure that both points have negative longitude values -------------------
            IPoint point = new PointClass();
            point.PutCoords(-170, 10); // Equivalent to 170 degrees WEST
            point.SpatialReference = WGS84;
            pointCollection.AddPoint(point);


            point = new PointClass();
            point.PutCoords(-200, 10); // Equivalent to 160 degrees EAST
            point.SpatialReference = WGS84;
            pointCollection.AddPoint(point);
            // -----------------------------------------------------------------------

            IPolyline polyline = (IPolyline)pointCollection;
            polyline.SpatialReference = WGS84;

            var geometryDefEdit = (IGeometryDefEdit)new GeometryDef();
            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
            geometryDefEdit.SpatialReference_2 = WGS84;

            var field = (IFieldEdit)new Field();
            field.Name_2 = "Shape";
            field.Type_2 = esriFieldType.esriFieldTypeGeometry;
            field.GeometryDef_2 = geometryDefEdit;

            var fields = (IFieldsEdit)new Fields();
            fields.AddField(field);

            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
            var featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile("C:\\Temp\\", 0);
            IFeatureClass featureClass = featureWorkspace.CreateFeatureClass
                        ("test3.shp", fields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

            var feature = featureClass.CreateFeature();
            feature.Shape = polyline;
            feature.Store();


            ArcMap.Application.CurrentTool = null;
        }
        /// <summary>
        /// Add Shapefile layer
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        private void AddShapeFileLayer(string path, string fileName)
        {
            try
            {
                // Create a new ShapefileWorkspaceFactory object and
                // open a shapefile folder - the path works with standard 9.3 installation
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)
                  workspaceFactory.OpenFromFile(path, 0);
                // Create a new FeatureLayer and assign a shapefile to it
                IFeatureLayer featureLayer = new ESRI.ArcGIS.Carto.FeatureLayer();
                featureLayer.FeatureClass = featureWorkspace.OpenFeatureClass(fileName);
                ILayer layer = (ILayer)featureLayer;
                layer.Name = featureLayer.FeatureClass.AliasName;
                // Add the Layer to the focus map
                IMap map = ArcMap.Document.FocusMap;

                map.AddLayer(layer);
            }
            catch (Exception e)
            {
                Log.WriteLine("AddShapeFileLayer: " + e.Message);
            }
        }
        private void AddTable(string strPath, string strFileName)
        {
            try
            {

                IWorkspaceFactory pFact = new ShapefileWorkspaceFactory();
                IWorkspace pWorkspace = pFact.OpenFromFile(strPath, 0);
                IFeatureWorkspace pFeatws = pWorkspace as IFeatureWorkspace;
                ITable ptable = pFeatws.OpenTable(strFileName);

                IMxDocument pmxdoc = ArcMap.Document as IMxDocument;
                IMap pmap = pmxdoc.FocusMap;

                IStandaloneTable pStTab = new StandaloneTableClass();
                pStTab.Table = ptable;
                IStandaloneTableCollection pStTabColl = pmap as IStandaloneTableCollection;
                pStTabColl.AddStandaloneTable(pStTab);
                pmxdoc.UpdateContents();

                ITableWindow2 ptableWindow = new TableWindowClass();
                ptableWindow.Application = ArcMap.Application;
                ptableWindow.StandaloneTable = pStTab;

                ptableWindow.Show(true);

                System.Runtime.InteropServices.Marshal.ReleaseComObject(pFact);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkspace);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatws);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(ptable);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pStTab);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pStTabColl);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(ptableWindow);

                GC.Collect();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
示例#35
0
        /// <summary>
        /// 获取工作空间SDE,文件型数据库,MDB,以及shapefile文件所在工作空间,这里可以用一个枚举
        /// </summary>
        /// <param name="_pDatabase"></param>
        /// <returns></returns>
        public IWorkspace GetWorkspace(String _pDatabase, GDBType pGDBType = GDBType.FGDB)
        {
            ESRI.ArcGIS.Geodatabase.IWorkspaceFactory pWsFactory = null;

            IWorkspace pWkspace = null;

            if (pGDBType == GDBType.SHP)
            {

                pWsFactory = new ShapefileWorkspaceFactory();

            }
            else if (pGDBType == GDBType.RWS)
            {

                pWsFactory = new RasterWorkspaceFactoryClass();

            }
            else if (pGDBType == GDBType.MDB)
            {
                pWsFactory = new AccessWorkspaceFactoryClass();
            }
            else if (pGDBType == GDBType.FGDB)
            {

                pWsFactory = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass();
            }
            else if (pGDBType == GDBType.SDE)
            {

                pWsFactory = new ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactoryClass();
            }

            try
            {

                pWkspace = pWsFactory.OpenFromFile(_pDatabase, 0);

            }
            catch (Exception EX)
            {
                //MessageBox.Show(EX.ToString());

            }

            return pWkspace;
        }
示例#36
0
文件: IDW.cs 项目: Krystal001025/temp
        public void CreateRasterFromPoints(IMap pMap, IFeatureLayer pp,String Path, String Name, String Field)
        {
            //1.��Shape�ļ���ȡ��FeatureClass
            //2.����FeatureClass����IFeatureClassDescriptor
            //3.����IRasterRaduis ����
            //����Cell
            //4.��ֵ�����ɱ���
            object obj = null;

            IWorkspaceFactory pShapSpace;

            pShapSpace = new ShapefileWorkspaceFactory();

            IWorkspace pW;

            pW = pShapSpace.OpenFromFile(Path, 0);

            IFeatureWorkspace pFeatureWork;

            pFeatureWork = pW as IFeatureWorkspace;

            IFeatureClass pFeatureClass = pFeatureWork.OpenFeatureClass("Name");

            IGeoDataset Geo = pFeatureClass as IGeoDataset;

            object extend = Geo.Extent;

            object o = null;

            IFeatureClassDescriptor pFeatureClassDes = new FeatureClassDescriptorClass();

            pFeatureClassDes.Create(pFeatureClass, null, Field);

            IRasterRadius pRasterrad = new RasterRadiusClass();

            pRasterrad.SetVariable(10, ref obj);

            object dCell = 0.5;//���Ը��ݲ�ͬ�ĵ�ͼ���������

            IInterpolationOp Pinterpla = new RasterInterpolationOpClass();

            IRasterAnalysisEnvironment pRasterAnaEn = Pinterpla as IRasterAnalysisEnvironment;

            pRasterAnaEn.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dCell);

            pRasterAnaEn.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extend, ref o);

            IGeoDataset pGRaster;

            object hh = 3;

            pGRaster = Pinterpla.IDW((IGeoDataset)pFeatureClassDes , 2, pRasterrad, ref hh);

            ISurfaceOp pSurF;

            pSurF = new RasterSurfaceOpClass();

            IGeoDataset pCour;

            object  o1 = 0;

            pCour = pSurF.Contour(pGRaster, 5, ref o1);

            IFeatureLayer pLa;

            pLa = new FeatureLayerClass();

            IFeatureClass pClass = pCour as IFeatureClass;

            pLa.FeatureClass = pClass;

            pLa.Name = pClass.AliasName;

            pMap.AddLayer(pLa as ILayer);
        }
示例#37
0
        /// <summary>
        /// 生成等值线
        /// </summary>
        /// <params name="targetworkspace"></params>
        /// <params name="nameOftargetFeatureClass"></params>
        /// <params name="sLayerAliasName"></params>
        private bool CreateContours(IWorkspace targetworkspace, string nameOftargetFeatureClass,
            string sLayerAliasName, string extent, ref string failInfo)
        {
            double douElevation;

            //设置一个最小值
            progressBarControl1.Properties.Minimum = 0;
            //设置一个最大值
            progressBarControl1.Properties.Maximum = 6;
            //设置步长,即每次增加的数
            progressBarControl1.Properties.Step = 1;
            //设置进度条的样式
            progressBarControl1.Properties.ProgressViewStyle = ProgressViewStyle.Solid;
            progressBarControl1.Position = 0;

            try
            {
                Geoprocessor GP = new Geoprocessor();

                if (withIn(m_strDataFilePath) == false)
                    return false;
                if (TB_Interval.Text == "")
                {
                    MessageBox.Show("请输入正确的等高距!", "提示!");
                    return false;
                }
                if (double.TryParse(TB_Interval.Text.Trim(), out douElevation))
                { }
                else
                {
                    TB_Interval.Text = null;
                    MessageBox.Show("请输入正确的等高距!", "提示!");
                    return false;
                }

                string featurOut = m_MakeContoursFolder + "\\Cont.shp";
                int k = 0;
                while (File.Exists(featurOut))
                {
                    k++;
                    featurOut = m_MakeContoursFolder + "\\Cont" + k.ToString() + ".shp";

                }
                int countCont = Directory.GetFiles(m_MakeContoursFolder, "Cont*").Length;
                if (countCont > 0)
                {
                    featurOut = m_MakeContoursFolder + "\\Cont" + countCont.ToString() + ".shp";
                }
                if (DrawContours.ConvertASCIIDescretePoint2FeatureClass(GP, m_strDataFilePath, featurOut) == false)
                    return false;
                //执行步长
                this.progressBarControl1.PerformStep();

                string ContourRaster = m_MakeContoursFolder + "\\Spline";
                //string ContourRaster = m_MakeContoursFolder + "\\" + nameOftargetFeatureClass + "_Render";
                if (extent != "")//右上左下  xmax  ymax  xmin  ymin
                    GP.SetEnvironmentValue("Extent", extent);
                bool suc = false;
                string sRasterLayerAliasName = sLayerAliasName + "渲染图";
                ILayer rsLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, sRasterLayerAliasName);
                if (rsLayer != null)
                {
                    DataEditCommon.g_pMap.DeleteLayer(rsLayer);
                }
                if (Directory.Exists(ContourRaster))
                {
                    try
                    {
                        Directory.Delete(ContourRaster, true);
                    }
                    catch
                    {
                        k = 1;
                        while (Directory.Exists(ContourRaster))
                        {
                            ContourRaster = m_MakeContoursFolder + "\\Spline" + k.ToString();
                            k++;
                        }
                    }
                }
                switch (CB_InterpolationMethod.Text)
                {
                    case "样条函数插值法":
                        suc = DrawContours.Interpolate2RasterSpline(GP, featurOut, ContourRaster, CB_SplineType.Text);
                        break;
                    case "自然邻域插值法":
                        suc = DrawContours.Interpolate2RasterNN(GP, featurOut, ContourRaster);
                        break;
                    case "克里格插值法":
                        suc = DrawContours.Interpolate2RasterKriging(GP, featurOut, ContourRaster,
                            CB_semiVariogramProp.Text, CB_searchRadiusProp.Text);
                        break;
                    case "反距离权重插值法":
                        suc = DrawContours.Interpolate2RasterIDW(GP, featurOut, ContourRaster);
                        break;
                    case "趋势面插值法":
                        suc = DrawContours.TrendToRaster(GP, featurOut, ContourRaster);
                        break;
                }
                if (suc == false)
                    return false;
                this.progressBarControl1.PerformStep();
                GP = new Geoprocessor();
                string R2Contour = m_MakeContoursFolder + "\\Contour.shp";
                k = 1;
                while (File.Exists(R2Contour))
                {
                    R2Contour = m_MakeContoursFolder + "\\Contour" + k.ToString() + ".shp";
                    k++;
                }
                int countContour = Directory.GetFiles(m_MakeContoursFolder, "Contour*").Length;
                if (countContour > 0)
                {
                    R2Contour = m_MakeContoursFolder + "\\Contour" + countContour.ToString() + ".shp";
                }

                if (DrawContours.SplineRasterToContour(GP, ContourRaster, R2Contour, douElevation) == false)
                    return false;
                this.progressBarControl1.PerformStep();

                string EvEContour = m_MakeContoursFolder + "\\EvEContour.shp";
                k = 1;
                while (File.Exists(EvEContour))
                {
                    EvEContour = m_MakeContoursFolder + "\\EvEContour" + k.ToString() + ".shp";
                    k++;
                }
                int countEvEContour = Directory.GetFiles(m_MakeContoursFolder, "EvEContour*").Length;
                if (countEvEContour > 0)
                {
                    EvEContour = m_MakeContoursFolder + "\\EvEContour" + countEvEContour.ToString() + ".shp";
                }
                if (DrawContours.FeaturesTo3D(GP, R2Contour, EvEContour) == false)
                    return false;
                this.progressBarControl1.PerformStep();

                //获得等值线Shp文件所在的工作空间
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
                IWorkspace sourceworkspace = workspaceFactory.OpenFromFile(m_MakeContoursFolder, 0);
                //裁切
                IPolygon bianjie = GetPolygon();

                //导入等值线Shp文件到数据库中
                DrawSpecialCommon drawspecial = new DrawSpecialCommon();
                string nameOfsourceFeatureClass = EvEContour.Substring(EvEContour.LastIndexOf("\\") + 1);
                nameOfsourceFeatureClass = nameOfsourceFeatureClass.Substring(0, nameOfsourceFeatureClass.LastIndexOf("."));
                bool Import = false;
                List<ziduan> list = new List<ziduan>
                {
                    new ziduan("BID", ""),
                    new ziduan("mingcheng", sLayerAliasName),
                    new ziduan("mcid", "0"),
                    new ziduan("date", DateTime.Now.ToString()),
                    new ziduan("type", CB_InterpolationMethod.Text)
                };
                list.Add(new ziduan("BID", ""));
                list.Add(new ziduan("mingcheng", sLayerAliasName));
                list.Add(new ziduan("mcid", "0"));
                list.Add(new ziduan("date", DateTime.Now.ToString()));
                list.Add(new ziduan("type", CB_InterpolationMethod.Text));
                IFeatureLayer pFeatureLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, EditLayerName) as IFeatureLayer;
                string WhereClause = "mcid='" + "0" + "'";

                DataEditCommon.DeleteFeatureByWhereClause(pFeatureLayer, WhereClause);
                if (radioBtnKJ.Checked && bianjie != null)
                    Import = IntersectAll(DataEditCommon.GetFeatureClassByName(sourceworkspace, nameOfsourceFeatureClass), bianjie, list);
                else
                    Import = drawspecial.ShapeImportGDB(sourceworkspace, targetworkspace, nameOfsourceFeatureClass, nameOftargetFeatureClass, list);
                this.progressBarControl1.PerformStep();

                if (Import == false)
                {
                    MessageBox.Show(sLayerAliasName + "导入数据库失败!");
                    DataEditCommon.g_axTocControl.Update();
                    DataEditCommon.g_pAxMapControl.Refresh();
                    failInfo = sLayerAliasName;
                    return false;
                }

                //添加相应的渲染图
                IRasterLayer newRasterLayer = new RasterLayerClass();
                newRasterLayer.CreateFromFilePath(ContourRaster);
                newRasterLayer = IntersectRaster(newRasterLayer, bianjie);
                //newRasterLayer.CreateFromDataset(newRasterDs);
                newRasterLayer.Name = sRasterLayerAliasName;
                UsingRasterStretchColorRampRender(newRasterLayer);
                //groupLayer.Add(newRasterLayer as ILayer);
                int indexPosition = DataEditCommon.g_pAxMapControl.LayerCount;//GroupLayer序号

                //判断MapControl中是否存在该图层
                ILayer mLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, sRasterLayerAliasName);
                if (mLayer != null)
                {
                    DataEditCommon.g_pMyMapCtrl.Map.DeleteLayer(mLayer);
                    indexPosition--;
                }
                DataEditCommon.g_pAxMapControl.AddLayer(newRasterLayer as ILayer, indexPosition);//添加到最下面
                DataEditCommon.g_pAxMapControl.ActiveView.Extent = newRasterLayer.AreaOfInterest;
                DataEditCommon.g_axTocControl.Update();
                DataEditCommon.g_pAxMapControl.Refresh();
                this.progressBarControl1.PerformStep();

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }
示例#38
0
        private void GetUniqueValueList()
        {
            //get all the unique value of the classitem

            if ((m_pEditLayer.classitem == null) || (m_pEditLayer.classitem.Length == 0))
                return;

            //label
            string strDataPath = Utility.GetAbsolutePathOfData(m_pEditLayer);
            IWorkspaceFactory pWsf = new ShapefileWorkspaceFactory();
            IWorkspace pWs = pWsf.OpenFromFile(strDataPath, 0);
            if (pWs != null)
            {
                IFeatureWorkspace pFws = pWs as IFeatureWorkspace;

                string strDataName = System.IO.Path.GetFileNameWithoutExtension(strDataPath);

                IFeatureClass pFeatureClass = pFws.OpenFeatureClass(strDataName);
                if (pFeatureClass != null)
                {
                    ICursor pCursor = pFeatureClass.Search(null, false) as ICursor;

                    IDataStatistics pDataStatistics = new DataStatisticsClass();
                    pDataStatistics.Field = m_pEditLayer.classitem;
                    pDataStatistics.Cursor = pCursor;
                    m_pUniqueEnumerator = pDataStatistics.UniqueValues;
                    //pDataStatistics
                }
            }
        }
示例#39
0
        /// <summary>
        /// 叠置分析
        /// </summary>
        /// <param name="axmapcontrol"></param>
        /// <param name="i">图层索引</param>
        /// <param name="name">输出图层名字</param>
        /// <returns></returns>
        public static FeatureLayer Stastic(AxMapControl axmapcontrol,int i,string name)
        {
            if (axmapcontrol == null || axmapcontrol.LayerCount < 2)
            {
                return null;
            }
               // pLayer = axmapcontrol.Map.Layer(0);
            ILayer pLayer = axmapcontrol.ActiveView.FocusMap.get_Layer(i);
            IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer;
            IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;

            ITable table = pFeatureClass as ITable;

            pLayer = axmapcontrol.ActiveView.FocusMap.get_Layer(axmapcontrol.LayerCount - 1);
            IFeatureLayer ppFeatureLayer=(IFeatureLayer)pLayer;
            IFeatureClass ppFeatureClass=ppFeatureLayer.FeatureClass;
            ITable ptable = (ITable)ppFeatureClass;

            //Intersect intersect=new Intersect()
            Double tol=0.0;
            IWorkspaceFactory wspfctry = new ShapefileWorkspaceFactory();
            IWorkspace pWorkSpace = wspfctry.OpenFromFile(SystemSet.Base_Map + "\\处理数据库\\实验数据", 0);

            IDataset pDataset = (IDataset)pWorkSpace;
            IName pName=pDataset.FullName;
            IDatasetName pDatasetName = new FeatureClassNameClass();
            pDatasetName.Name = name;
            pDatasetName.WorkspaceName = (IWorkspaceName)pName;
            IFeatureClassName fcn = (IFeatureClassName)pDatasetName;
            IBasicGeoprocessor pBG=new BasicGeoprocessor();
            IFeatureClass pOutFeatureClass = pBG.Intersect(table, false, ptable, false, tol, fcn);
            IFeatureLayer pOutFeatLayer = new FeatureLayerClass();
            FeatureLayer featurelayer = (FeatureLayer)pOutFeatLayer;
            featurelayer.FeatureClass = pOutFeatureClass;
            featurelayer.Name = pOutFeatureClass.AliasName;
            return featurelayer;
        }
示例#40
0
        public void CheckforGeoSpatialData(String strPath, String geoType, ListBox lstBox)
        {
            IWorkspaceFactory owrkspaceFact = null;
            IFeatureWorkspace theFWS;
            IFeatureClass theFClass;
            int FCount;

            try
            {
                switch (geoType)
                {
                    case "ShapeFile":
                        owrkspaceFact = new ShapefileWorkspaceFactory();
                        break;
                    default:
                        owrkspaceFact = new AccessWorkspaceFactoryClass();
                        break;
                }

                PropertySet pPropSet = new PropertySetClass();
                pPropSet.SetProperty("DATABASE", strPath);

                IWorkspace theWS = owrkspaceFact.Open(pPropSet, 0);
                theFWS = (IFeatureWorkspace)theWS;

                if (theWS != null)
                {
                    String[] theSrcNames = GeoDbProcs.GetFeatureClassNames(theWS);

                    foreach (String theSrcName in theSrcNames)
                    {
                        theFClass = theFWS.OpenFeatureClass(theSrcName);
                        lbSource.Items.Add(new FeatureData(theSrcName, theFClass));
                        Application.DoEvents();
                    }
                }
            }
            catch { }
        }
        private void setupmap()
        {
            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace workspace = workspaceFactory.OpenFromFile(@"C:\Users\huty\Desktop\武汉实习数据", 0);
            IFeatureWorkspace featureworkspace = (IFeatureWorkspace)workspace;

            mainroad = featureworkspace.OpenFeatureClass("主干道.shp");
            mainroadlayer = new FeatureLayerClass();
            mainroadlayer.FeatureClass = mainroad;
            mainroadlayer.Name = "mainroad";

            secondroad = featureworkspace.OpenFeatureClass("次干道.shp");
            secondroadlayer = new FeatureLayerClass();
            secondroadlayer.FeatureClass = secondroad;
            secondroadlayer.Name = "secondroad";

            waterregion = featureworkspace.OpenFeatureClass("水域.shp");
            waterregionlayer = new FeatureLayerClass();
            waterregionlayer.FeatureClass = waterregion;
            waterregionlayer.Name = "waterregion";

            supermarket = featureworkspace.OpenFeatureClass("超市.shp");
            supermarketlayer = new FeatureLayerClass();
            supermarketlayer.FeatureClass = supermarket;
            supermarketlayer.Name = "supermarket";

            address = featureworkspace.OpenFeatureClass("地名.shp");
            addresslayer = new FeatureLayerClass();
            addresslayer.FeatureClass = address;
            addresslayer.Name = "address";

            hotel = featureworkspace.OpenFeatureClass("饭店.shp");
            hotellayer = new FeatureLayerClass();
            hotellayer.FeatureClass = hotel;
            hotellayer.Name = "hotel";

            trainstation = featureworkspace.OpenFeatureClass("火车站.shp");
            trainstationlayer = new FeatureLayerClass();
            trainstationlayer.FeatureClass = trainstation;
            trainstationlayer.Name = "trainstation";

            bank = featureworkspace.OpenFeatureClass("金融银行.shp");
            banklayer = new FeatureLayerClass();
            banklayer.FeatureClass = bank;
            banklayer.Name = "bank";

            sight = featureworkspace.OpenFeatureClass("景点.shp");
            sightlayer = new FeatureLayerClass();
            sightlayer.FeatureClass = sight;
            sightlayer.Name = "sight";

            busstation = featureworkspace.OpenFeatureClass("汽车站.shp");
            busstationlayer = new FeatureLayerClass();
            busstationlayer.FeatureClass = busstation;
            busstationlayer.Name = "busstation";

            government = featureworkspace.OpenFeatureClass("区政府.shp");
            governmentlayer = new FeatureLayerClass();
            governmentlayer.FeatureClass = government;
            governmentlayer.Name = "government";

            hospital = featureworkspace.OpenFeatureClass("医院.shp");
            hospitallayer = new FeatureLayerClass();
            hospitallayer.FeatureClass = hospital;
            hospitallayer.Name = "hospital";

            recreation = featureworkspace.OpenFeatureClass("娱乐场所.shp");
            recreationlayer = new FeatureLayerClass();
            recreationlayer.FeatureClass = recreation;
            recreationlayer.Name = "recreation";

            railway = featureworkspace.OpenFeatureClass("铁路.shp");
            railwaylayer = new FeatureLayerClass();
            railwaylayer.FeatureClass = railway;
            railwaylayer.Name = "railway";
        }
示例#42
0
        public static void cp(IPolygon pPolygon)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Shape文件(*.shp)|*.shp";
            saveFileDialog.Title = "新建面shp文件";
            saveFileDialog.CheckFileExists = true;
            saveFileDialog.RestoreDirectory = true;
            DialogResult dialogResult = saveFileDialog.ShowDialog();
            string shpPath;
            string shpName;
            IWorkspaceFactory pWorkSpaceFactory = new ShapefileWorkspaceFactory();
            if (dialogResult == DialogResult.OK)
            {
                IFeatureClass pFeatureClass;
                string date = DateTime.Now.ToLongDateString().ToString();
                //saveFileDialog.FileName = date + "采集的坐标点";
                string fileFullName = saveFileDialog.FileName;
                int index = fileFullName.LastIndexOf("\\");
                shpName = fileFullName.Substring(index + 1);
                shpPath = fileFullName.Substring(0, index);
                IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkSpaceFactory.OpenFromFile(shpPath, 0);
                IWorkspaceEdit pWorkspaceEdit = (IWorkspaceEdit)pFeatureWorkspace;
                IGeometryDef pGeometryDef = new GeometryDef();
                IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit;
                pGeometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;//点、线、面什么的

                ISpatialReferenceFactory2 ipSpaRefFa = new SpatialReferenceEnvironmentClass();
                IGeographicCoordinateSystem ipGeoCorSys = new GeographicCoordinateSystemClass();

                ipGeoCorSys = ipSpaRefFa.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
                ISpatialReference ipSpaRef = ipGeoCorSys;
                pGeometryDefEdit.SpatialReference_2 = ipSpaRef;

                /*if (System.IO.File.Exists(saveFileDialog.FileName))
                {
                    if (MessageBox.Show("是否替换原文件?", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {

                        pFeatureClass = pFeatureWorkspace.OpenFeatureClass(shpName);
                        IDataset pDataset = (IDataset)pFeatureClass;
                        pDataset.Delete();
                    }
                    else
                        return;
                }
                else
                {
                    fileFullName = null;
                    return;
                }*/

                //设置字段

                double area;
                IFields pFields = new FieldsClass();
                IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;

                IField pField = new FieldClass();
                IFieldEdit pFieldEdit = (IFieldEdit)pField;
                pFieldEdit.Name_2 = "SHAPE";
                pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
                pFieldEdit.GeometryDef_2 = pGeometryDef;
                pFieldsEdit.AddField(pField);

                pField = new FieldClass();
                pFieldEdit = (IFieldEdit)pField;
                pFieldEdit.Name_2 = "面积";
                pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                pFieldsEdit.AddField(pField);
                //创建shp
                pWorkspaceEdit.StartEditOperation();//启动编辑

                pFeatureClass = pFeatureWorkspace.CreateFeatureClass(shpName, pFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");

                pPolygon = new PolygonClass();
                IArea s = pPolygon as IArea;
                area = s.Area;
                IFeature pfeature = pFeatureClass.CreateFeature();
                pfeature.Shape = pPolygon;
                pfeature.set_Value(pfeature.Fields.FindField("面积"), area.ToString());
                pfeature.Store();
                pWorkspaceEdit.StopEditOperation();
                IFeatureLayer pFeaturelayer = new FeatureLayerClass();
                pFeaturelayer.FeatureClass = pFeatureClass;
                pFeaturelayer.Name = "采集坐标图层";

            }
        }
示例#43
0
文件: GisUtils.cs 项目: ezequias/Esri
        public static IFeatureWorkspace GetFeatureWoskspacePasta(string pasta)
        {
            IFeatureWorkspace pFeatureWorkspace;

            IPropertySet pPropset = new PropertySetClass();
            IWorkspace pWorkspace = null;

            pPropset.SetProperty("DATABASE", pasta);

            IWorkspaceFactory pFact = new ShapefileWorkspaceFactory();
            pWorkspace = pFact.Open(pPropset, 0);

            pFeatureWorkspace = pWorkspace as IFeatureWorkspace;

            return pFeatureWorkspace;
        }
示例#44
0
        /// <summary>
        /// 连接Shp的Workspace
        /// </summary>
        /// <param name="Path">Shp路径</param>
        public IWorkspace Workspace_SHP(string Path)
        {
            IWorkspaceFactory WorkspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace WS = null;

            try
            {
                WS = WorkspaceFactory.OpenFromFile(Path, 0);
            }
            catch
            {
                MessageBox.Show("请检查Shp路径是否正确");
            }

            return WS;
        }
示例#45
0
        public static void Mlayer_IDW_Click()
        {
            // 用反距离IDW插值生成的栅格图像。如下:
               IInterpolationOp pInterpolationOp = new RasterInterpolationOpClass();

               IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
               string pPath = Application.StartupPath + @"\MakeContours\Cont.shp";
               string pFolder = System.IO.Path.GetDirectoryName(pPath);
               string pFileName = System.IO.Path.GetFileName(pPath);

               IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(pFolder, 0);

               IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
               IFeatureClass oFeatureClass = pFeatureWorkspace.OpenFeatureClass(pFileName);
               IFeatureClassDescriptor pFCDescriptor = new FeatureClassDescriptorClass();
               pFCDescriptor.Create(oFeatureClass, null, "shape.z");
               IRasterRadius pRadius = new RasterRadiusClass();

               object objectMaxDistance = null;
               object objectbarrier = null;
               object missing = Type.Missing;
               pRadius.SetVariable(12, ref objectMaxDistance);

               object dCellSize =1;
               object snapRasterData = Type.Missing;
               IEnvelope pExtent;
               pExtent = new EnvelopeClass();
               Double xmin = 27202;
               Double xmax = 31550;

               Double ymin = 19104;
               Double ymax = 22947;
               pExtent.PutCoords(xmin, ymin, xmax, ymax);
               object extentProvider = pExtent;
               IRasterAnalysisEnvironment pEnv = pInterpolationOp as IRasterAnalysisEnvironment;
               pEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dCellSize);
               pEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData);
               IGeoDataset poutGeoDataset = pInterpolationOp.IDW((IGeoDataset)pFCDescriptor, 2, pRadius, ref objectbarrier);
               ISurfaceOp surOp = new RasterSurfaceOpClass();

               IRaster pOutRaster = poutGeoDataset as IRaster;

               IRasterLayer pOutRasLayer = new RasterLayer();
               pOutRasLayer.CreateFromRaster(pOutRaster);

               IMap pMap = Common.DataEditCommon.g_pMap;
               pMap.AddLayer(pOutRasLayer);
               Common.DataEditCommon.g_axTocControl.Refresh();
               Common.DataEditCommon.g_pAxMapControl.ActiveView.Refresh();
        }
示例#46
0
        public static void Mlayer_Krige_Click()
        {
            // 用克里金Krige插值生成的栅格图像。如下:
               IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
               string pPath = Application.StartupPath + @"\MakeContours\Cont.shp";
               string pFolder = System.IO.Path.GetDirectoryName(pPath);
               string pFileName = System.IO.Path.GetFileName(pPath);
               IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(pFolder, 0);
               IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
               IFeatureClass oFeatureClass = pFeatureWorkspace.OpenFeatureClass(pFileName);
               IFeatureClassDescriptor pFCDescriptor = new FeatureClassDescriptorClass();
               pFCDescriptor.Create(oFeatureClass, null, "shape.z");

               IInterpolationOp pInterpolationOp = new RasterInterpolationOpClass();
               IRasterAnalysisEnvironment pEnv = pInterpolationOp as IRasterAnalysisEnvironment;

               object Cellsize = 0.004;//Cell size for output raster;0.004
               pEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref Cellsize);
               //设置输出范围
               //27202 19104;27202 22947;31550 22947;31550 19104
               object snapRasterData = Type.Missing;
               IEnvelope pExtent;
               pExtent = new EnvelopeClass();
               Double xmin = 27202;
               Double xmax = 31550;

               Double ymin = 19104;
               Double ymax = 22947;
               pExtent.PutCoords(xmin, ymin, xmax, ymax);
               object extentProvider = pExtent;
               pEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData);
               Double dSearchD = 10;
               object pSearchCount = 3;
               object missing = Type.Missing;
               IRasterRadius pRadius = new RasterRadius();
               pRadius.SetFixed(dSearchD, ref pSearchCount);
               //pRadius.SetVariable((int)pSearchCount, ref dSearchD);

               IGeoDataset poutGeoDataset = pInterpolationOp.Krige((IGeoDataset)pFCDescriptor, esriGeoAnalysisSemiVariogramEnum.esriGeoAnalysisGaussianSemiVariogram, pRadius, false, ref missing);

               IRaster pOutRaster = poutGeoDataset as IRaster;
               IRasterLayer pOutRasLayer = new RasterLayer();
               pOutRasLayer.CreateFromRaster(pOutRaster);

               IMap pMap = Common.DataEditCommon.g_pMap;
               pMap.AddLayer(pOutRasLayer);
               Common.DataEditCommon.g_axTocControl.Refresh();
               Common.DataEditCommon.g_pAxMapControl.ActiveView.Refresh();
        }
示例#47
0
        /// <summary>
        /// 通过TIN文件,建立*.shp文件
        /// </summary>
        /// <param name="TINDir">TIN文件的文件夹路径</param>
        private void CreateContourData(string TINDir)
        {
            try
            {
                IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
                CopyFolder(Application.StartupPath + "\\Convert\\TemContour", Application.StartupPath + "\\Convert\\ContourResult\\" + this.Random);
                IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(Application.StartupPath + "\\Convert\\ContourResult\\" + this.Random, 0);
                IWorkspaceEdit w = pWorkspace as IWorkspaceEdit;
                IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
                IFeatureClass tFeatureClass = pFeatureWorkspace.OpenFeatureClass("Contour.shp");

                ITinWorkspace pTinWorkspace;
                IWorkspace pWS;
                IWorkspaceFactory pWSFact = new TinWorkspaceFactoryClass();

                pWS = pWSFact.OpenFromFile(TINDir, 0);

                ITin pTin;

                pTinWorkspace = pWS as ITinWorkspace;
                w.StartEditing(true);
                w.StartEditOperation();

                if (pTinWorkspace.get_IsTin(this.Random))
                {
                    pTin = pTinWorkspace.OpenTin(this.Random);

                    ITinSurface pTinSurface = pTin as ITinSurface;

                    pTinSurface.Contour(0, this.Interval, tFeatureClass, "Z", 0);

                    w.StopEditOperation();
                    w.StopEditing(true);
                }
            }
            catch (Exception)
            {

            }
        }
示例#48
0
        //���һ����ͼ�㵽mapfile
        public bool addLayer(string dataPath)
        {
            if (_Map == null)
            {
                if (ErrorOccured != null)
                    ErrorOccured(null, new MSErrorEventArgs("û�д�mapfile"));

                return false;
            }

            layerObj pLayer = new layerObj(_Map);
            pLayer.status = 1;

            string strName = Path.GetFileNameWithoutExtension(dataPath);
            pLayer.name = strName;
            pLayer.group = strName;

            string strExt = Path.GetExtension(dataPath).ToLower();
            //wanliyun:2009.05.06
            //add the mapinfo tab format support
            if ((strExt == ".shp") || (strExt == ".tab"))
            {
                IFeatureClass pFc = null;

                if (strExt == ".shp")
                {
                    IWorkspaceFactory pWsf = new ShapefileWorkspaceFactory();
                    IFeatureWorkspace pFws = pWsf.OpenFromFile(dataPath, 0) as IFeatureWorkspace;
                    pFc = pFws.OpenFeatureClass(strName);

                    pLayer.connectiontype = MS_CONNECTION_TYPE.MS_SHAPEFILE;
                    pLayer.data = dataPath;
                }
                else if (strExt == ".tab")
                {
                    IWorkspaceFactory pWsf = new OgrWorkspaceFactory();
                    IFeatureWorkspace pFws = pWsf.OpenFromFile(dataPath, 0) as IFeatureWorkspace;

                    pFc = pFws.OpenFeatureClass(strName);

                    pLayer.connectiontype = MS_CONNECTION_TYPE.MS_OGR;
                    pLayer.connection = dataPath;
                }

                IEnvelope pEnvelope = ((IGeoDataset)pFc).Extent;

                if (_Map.numlayers == 1)
                {
                    _Map.extent.minx = pEnvelope.XMin;
                    _Map.extent.miny = pEnvelope.YMin;
                    _Map.extent.maxx = pEnvelope.XMax;
                    _Map.extent.maxy = pEnvelope.YMax;
                }
                else
                {
                    //if the layer extents lager than the map extents
                    //reset the map extents
                    if (pEnvelope.XMin < _Map.extent.minx)
                        _Map.extent.minx = pEnvelope.XMin;
                    if (pEnvelope.YMin < _Map.extent.miny)
                        _Map.extent.miny = pEnvelope.YMin;
                    if (pEnvelope.XMax > _Map.extent.maxx)
                        _Map.extent.maxx = pEnvelope.XMax;
                    if (pEnvelope.YMax > _Map.extent.maxy)
                        _Map.extent.maxy = pEnvelope.YMax;

                }

                //rerecord the max extents
                m_MapMinx = _Map.extent.minx;
                m_MapMiny = _Map.extent.miny;
                m_MapMaxx = _Map.extent.maxx;
                m_MapMaxy = _Map.extent.maxy;

                classObj myClass = new classObj(pLayer);
                myClass.name = "random";

                styleObj myStyle = new styleObj(myClass);
                Color pRandomColor = GetRandomColor();
                myStyle.color.red = pRandomColor.R;
                myStyle.color.green = pRandomColor.G;
                myStyle.color.blue = pRandomColor.B;

                myStyle.opacity = 0;

                fmapGeometryType pGeomType = pFc.ShapeType;

                if ((pGeomType == fmapGeometryType.Point) ||
                    (pGeomType == fmapGeometryType.Point25D) ||
                    (pGeomType == fmapGeometryType.MultiPoint) ||
                    (pGeomType == fmapGeometryType.MultiPoint25D))
                {
                    pLayer.type = MS_LAYER_TYPE.MS_LAYER_POINT;
                }
                else if ((pGeomType == fmapGeometryType.LineString) ||
                        (pGeomType == fmapGeometryType.LineString) ||
                        (pGeomType == fmapGeometryType.MultiLineString) ||
                        (pGeomType == fmapGeometryType.MultiLineString25D))
                {
                    pLayer.type = MS_LAYER_TYPE.MS_LAYER_LINE;
                }
                else if ((pGeomType == fmapGeometryType.Polygon) ||
                        (pGeomType == fmapGeometryType.Polygon25D) ||
                        (pGeomType == fmapGeometryType.MultiPolygon) ||
                        (pGeomType == fmapGeometryType.MultiPolygon25D))
                {
                    pRandomColor = GetRandomColor();
                    myStyle.outlinecolor.red = pRandomColor.R;
                    myStyle.outlinecolor.green = pRandomColor.G;
                    myStyle.outlinecolor.blue = pRandomColor.B;

                    pLayer.type = MS_LAYER_TYPE.MS_LAYER_POLYGON;
                }
                else
                {
                    pLayer.type = MS_LAYER_TYPE.MS_LAYER_POLYGON;
                }

                if (pFc != null)
                    pFc.Dispose();
            }
            else if ((strExt == ".tif") || (strExt == ".img"))
            {
                pLayer.data = dataPath;
                pLayer.connectiontype = MS_CONNECTION_TYPE.MS_RASTER;
                pLayer.type = MS_LAYER_TYPE.MS_LAYER_RASTER;
            }
            else
                return false;

            if (OnLayerChanged != null)
                OnLayerChanged(null, new LayerChangedEventArgs(pLayer.index,strName, true));

            RecordLayersState();
            //Console.WriteLine(_Map.numlayers.ToString());

            return true;
        }
示例#49
0
        /// <summary>
        /// 创建等高线*.shp文件的主方法
        /// </summary>
        /// <param name="lux">左上投影x坐标</param>
        /// <param name="luy">左上投影y坐标</param>
        /// <param name="luz">左上投影z坐标</param>
        /// <param name="rlx">右下投影x坐标</param>
        /// <param name="rly">右下投影y坐标</param>
        /// <param name="rlz">右下投影z坐标</param>
        /// <param name="m_interval">采样间隔</param>
        /// <returns>等高线*.shp文件的文件名</returns>
        public string CreateContourShape(ISGWorld61 sgworld, double lux, double luy, double luz, double rlx, double rly, double rlz,double m_interval)
        {
            double width = sgworld.CoordServices.GetDistance(lux, luy, rlx, luy);
            double hight = sgworld.CoordServices.GetDistance(lux, luy, lux, rly);
            if (width<5||hight<10)
            {
                MessageBox.Show("范围过小!","SUNZ",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                return null;

            }
            if ((width/1000)*(hight/1000)>40)
            {
                if (MessageBox.Show("范围超出40平分公里,系统计算时间比较长,是否继续?","提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question) == DialogResult.OK)
                {

                }
                else
                {
                    return null;
                }
            }
            this.Interval = m_interval;
            this.Random = System.Guid.NewGuid().ToString().Substring(0, 6).ToLower();
            CopyFolder(Application.StartupPath + "\\Convert\\TemPoints", Application.StartupPath + "\\Convert\\PointsResult\\" + this.Random);
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(Application.StartupPath + "\\Convert\\PointsResult\\" + this.Random, 0);
            IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
            IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(Application.StartupPath + "\\Convert\\PointsResult\\" + Random + "\\TemPointLayer.shp"));
            IFeatureClassWrite fr = (IFeatureClassWrite)pFeatureClass;
            IWorkspaceEdit w = (pFeatureClass as IDataset).Workspace as IWorkspaceEdit;
            IFeature f;
            w.StartEditing(true);
            w.StartEditOperation();
            int EastPointCount = (int)(width / 5);
            int NothPointCount = (int)(hight / 5);
            for (int j = 0; j < NothPointCount; j++)
            {
                ESRI.ArcGIS.Geometry.IPoint p;
                p = new ESRI.ArcGIS.Geometry.PointClass();
                ESRI.ArcGIS.Geometry.IZAware iz = p as ESRI.ArcGIS.Geometry.IZAware;
                iz.ZAware = true;
                p.X = lux;
                p.Y = luy;
                p.Z = luz;

                ESRI.ArcGIS.Geometry.IGeometry peo;
                peo = p;
                f = pFeatureClass.CreateFeature();
                f.Shape = peo;
                f.set_Value(3, p.Z);
                f.Store();
                fr.WriteFeature(f);

                for (int i = 0; i < EastPointCount; i++)
                {

                    IPosition61 positionLU = null;
                    ICoord2D pPoint = null;
                    if ((j + 2) % 2 == 0)
                    {
                        pPoint = sgworld.CoordServices.MoveCoord(lux, luy, 5, 0);
                    }
                    else
                    {
                        pPoint = sgworld.CoordServices.MoveCoord(lux, luy, -5, 0);
                    }

                    IWorldPointInfo61 pW = sgworld.Terrain.GetGroundHeightInfo(pPoint.X, pPoint.Y, AccuracyLevel.ACCURACY_BEST_FROM_MEMORY, true);
                    positionLU = pW.Position;
                    luz = positionLU.Altitude;
                    lux = positionLU.X;
                    luy = positionLU.Y;
                    p = new ESRI.ArcGIS.Geometry.PointClass();
                    iz = p as ESRI.ArcGIS.Geometry.IZAware;
                    iz.ZAware = true;
                    p.X = lux;
                    p.Y = luy;
                    p.Z = luz;
                    peo = p;
                    f = pFeatureClass.CreateFeature();
                    f.Shape = peo;
                    f.set_Value(3, p.Z);
                    f.Store();
                    fr.WriteFeature(f);

                }
                ICoord2D pPointL = sgworld.CoordServices.MoveCoord(lux, luy, 0, -5);
                IWorldPointInfo61 pWL = sgworld.Terrain.GetGroundHeightInfo(pPointL.X, pPointL.Y, AccuracyLevel.ACCURACY_FORCE_BEST_RENDERED, true);
                luz = pWL.Position.Altitude;
                lux = pWL.Position.X;
                luy = pWL.Position.Y;

            }
            w.StopEditOperation();
            w.StopEditing(true);
            CreateTinFromFeature(pFeatureClass);
            return this.Random;
        }
示例#50
0
        //�����������Ч����¥�ϵ�1/50������
        //public static string GetAbsolutePath(string dir, string path)
        //{
        //string strDir = Directory.GetCurrentDirectory();
        //Directory.SetCurrentDirectory(dir);
        //string strNew = Path.GetFullPath(path);
        //Directory.SetCurrentDirectory(strDir);
        //return strNew;
        //}
        /// <summary>
        /// get all fields' name of the layer
        /// </summary>
        /// <param name="layer"></param>
        /// <returns></returns>
        public static StringCollection GetFieldsOfLayer(layerObj layer)
        {
            StringCollection pStringCollection = new StringCollection();

            string strDataPath = GetAbsolutePathOfData(layer);

            IWorkspaceFactory pWsf = new ShapefileWorkspaceFactory();
            IWorkspace pWs = pWsf.OpenFromFile(Path.GetDirectoryName(strDataPath), 0);
            if (pWs != null)
            {
                IFeatureWorkspace pFws = pWs as IFeatureWorkspace;

                string strDataName = Path.GetFileNameWithoutExtension(strDataPath);

                IFeatureClass pFeatureClass = pFws.OpenFeatureClass(strDataName);
                if (pFeatureClass != null)
                {
                    IFields pFields = pFeatureClass.Fields;
                    if(pFields != null)
                    {
                        int iCount = pFields.FiledCount;
                        for (int i = 0; i < iCount; i++)
                        {
                            pStringCollection.Add(pFields.GetField(i).Name);
                        }
                    }

                }
            }

            return pStringCollection;
        }
示例#51
0
 //
 //�򿪹�������
 //
 public static IWorkspace OpenWorkspace(string strWorkspaceName)
 {
     IWorkspaceFactory workspaceFactory;
     workspaceFactory = new ShapefileWorkspaceFactory();
     return workspaceFactory.OpenFromFile(strWorkspaceName, 0);
 }
示例#52
0
        private void Create_Click(object sender, EventArgs e)
        {
            try
            {
                IWorkspaceFactory pShpWksFact = new ShapefileWorkspaceFactory();
                IFeatureWorkspace pFeatWks;
                pFeatWks = (IFeatureWorkspace)pShpWksFact.OpenFromFile(filePath, 0);
                const string strShapeFieldName = "Shape";
                //定义属性字段
                IFields pFields = new Fields();
                IFieldsEdit pFieldsEdit;
                pFieldsEdit = pFields as IFieldsEdit;
                IField pField = new Field();
                IFieldEdit pFieldEdit = new Field() as IFieldEdit;
                pFieldEdit.Name_2 = strShapeFieldName;
                pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
                pField = pFieldEdit as IField;
                //定义几何属性
                IGeometryDef pGeomDef = new GeometryDef();
                IGeometryDefEdit pGeomDefEdit = new GeometryDef() as IGeometryDefEdit;
                pGeomDefEdit = pGeomDef as IGeometryDefEdit;
                switch (shpTypeComboBox.Text)
                {
                    case "Point":
                        pGeomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
                        break;
                    case "Polyline":
                        pGeomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
                        break;
                    case "Polygon":
                        pGeomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
                        break;
                }

                pGeomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
                pGeomDefEdit.SpatialReference_2 = new UnknownCoordinateSystem() as ISpatialReference;
                pFieldEdit.GeometryDef_2 = pGeomDef;
                pFieldsEdit.AddField(pField);
                pFields = pFieldsEdit as IFields;
                IFeatureClass pFeatureClass;
                pFeatureClass = pFeatWks.CreateFeatureClass(fileName, pFields, null, null,
                    esriFeatureType.esriFTSimple, strShapeFieldName, "");
                //添加属性字段
                for (int i = 0; i < addFieldListBox.Items.Count; i++)
                {
                    IField pfield = new Field();
                    IFieldEdit pfieldEdit = new Field() as IFieldEdit;
                    pfieldEdit.Name_2 = addFieldListBox.Items[i].ToString();
                    pfieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    pfield = pfieldEdit as IField;
                    pFeatureClass.AddField(pfield);
                }
                //绘制点
                for (int i = 0; i < excelDataGridViewX.Rows.Count - 1; i++)
                {
                    DataGridViewRow dataRow = excelDataGridViewX.Rows[i];
                    double pointX, pointY;
                    pointX = double.Parse(dataRow.Cells[xComboBoxEx.Text].Value.ToString());
                    pointY = double.Parse(dataRow.Cells[yComboBoxEx.Text].Value.ToString());

                    IPoint pPoint = new ESRI.ArcGIS.Geometry.Point() as IPoint;
                    pPoint.PutCoords(pointX, pointY);
                    IFeature pFeature = pFeatureClass.CreateFeature();
                    pFeature.Shape = pPoint;
                    //为该点添加属性值
                    for (int j = 0; j < addFieldListBox.Items.Count; j++)
                    {
                        string fieldName = addFieldListBox.Items[j].ToString();
                        pFeature.set_Value(pFeature.Fields.FindField(fieldName),
                            dataRow.Cells[fieldName].Value.ToString());
                    }
                    pFeature.Store();
                }
                //添加新建的数据至Map中
                axMapControl.AddShapeFile(filePath, fileName);
                this.Hide();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void DeleteShapeFile(string shapeFilePath)
        {
            string fcName = System.IO.Path.GetFileName(shapeFilePath);
            string folderName = System.IO.Path.GetDirectoryName(shapeFilePath);

            using (ComReleaser oComReleaser = new ComReleaser())
            {
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
                IWorkspace workspace = workspaceFactory.OpenFromFile(folderName, 0);
                IFeatureWorkspace fWorkspace = (IFeatureWorkspace)workspace;
                IDataset ipDs = fWorkspace.OpenFeatureClass(fcName) as IDataset;
                ipDs.Delete();

                File.Delete(shapeFilePath);

                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workspace);
                workspace = null;
                fWorkspace = null;
                ipDs = null;
            }
 
            GC.Collect();
            
        }
        public static void addShapeFileToLayer(string sPath, String sShapeName, bool isVisible = false)
        {
            IWorkspaceFactory pWorkspaceFactory;
            IFeatureWorkspace pFeatureWorkspace;
            IFeatureLayer pFeaturelayer;

            try
            {
                // Create a new ShapefileWorkspaceFactory object and open a shapefile folder
                pWorkspaceFactory = new ShapefileWorkspaceFactory();
                pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(sPath, 0);

                // Create a new FeatureLayer and assign a shapefile to it
                pFeaturelayer = new FeatureLayer();
                pFeaturelayer.FeatureClass = pFeatureWorkspace.OpenFeatureClass(sShapeName);
                pFeaturelayer.Name = pFeaturelayer.FeatureClass.AliasName;
                pFeaturelayer.Visible = isVisible;

                // Add the FeatureLayer to the focus map
                SF10_extMain.m_pDoc.AddLayer(pFeaturelayer);
                SF10_extMain.m_pDoc.UpdateContents();
            }
            catch
            {
            }

            pWorkspaceFactory = null;
            pFeatureWorkspace = null;
            pFeaturelayer = null;
        }
        public static IFeatureClass createNewEmptyShapefilePoint(string sP, string sN, int sPj)
        {
            String strFolder;
            String strName;
            const string strShapeFieldName = "Shape";

            try
            {
                strFolder = sP;
                strName = sN;

                // Open the folder to contain the shapefile as a workspace
                IFeatureWorkspace pFWS;
                IWorkspaceFactory pWorkspaceFactory;
                pWorkspaceFactory = new ShapefileWorkspaceFactory();
                pFWS = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(strFolder, 0);

                // Set up a simple fields collection
                IFields pFields;
                IFieldsEdit pFieldsEdit;
                pFields = new Fields();
                pFieldsEdit = (IFieldsEdit)pFields;

                IField pField;
                IFieldEdit pFieldEdit;

                // Make the shape field
                // it will need a geometry definition, with a spatial reference

                pField = new Field();
                pFieldEdit = (IFieldEdit)pField;
                pFieldEdit.Name_2 = strShapeFieldName;
                pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

                IGeometryDef pGeomDef;
                IGeometryDefEdit pGeomDefEdit;
                pGeomDef = new GeometryDef();
                pGeomDefEdit = (IGeometryDefEdit)pGeomDef;

                pGeomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; //Creates point shapefile

                if (sPj == 0)
                {
                    pGeomDefEdit.SpatialReference_2 = new UnknownCoordinateSystemClass();
                }
                else
                {
                    ISpatialReferenceFactory2 pSpatRefFact;
                    pSpatRefFact = new SpatialReferenceEnvironment() as ISpatialReferenceFactory2;
                    IProjectedCoordinateSystem pGeoCoordSys;
                    pGeoCoordSys = pSpatRefFact.CreateProjectedCoordinateSystem(sPj);
                    pGeomDefEdit.SpatialReference_2 = pGeoCoordSys;
                }

                pFieldEdit.GeometryDef_2 = pGeomDef;
                pFieldsEdit.AddField(pField);

                // Add another miscellaneous text field
                pField = new Field();
                pFieldEdit = (IFieldEdit)pField;
                pFieldEdit.Length_2 = 25;
                pFieldEdit.Name_2 = "TextField";
                pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                pFieldsEdit.AddField(pField);

                // Create the shapefile
                return pFWS.CreateFeatureClass(strName, pFields, null, null, esriFeatureType.esriFTSimple, strShapeFieldName, "");
            }
            catch
            { return null; }
        }
        public static ITable ouvrirDbf(string sCheminDbf)
        {
            IWorkspaceFactory pFact;
            IWorkspace pWorkspace;
            IFeatureWorkspace pFeatws;
            ITable pTable;

            pFact = new ShapefileWorkspaceFactory();
            pWorkspace = pFact.OpenFromFile(System.IO.Path.GetDirectoryName(sCheminDbf), 0);

            pFeatws = (IFeatureWorkspace)pWorkspace;
            pTable = pFeatws.OpenTable(System.IO.Path.GetFileName(sCheminDbf));

            return pTable;
        }
        private void ExportTable2DBF(ITable ptable, string strPath, string strFilename)
        {
            IDataset pDataset = ptable as IDataset;
            IDatasetName pDatasetName = pDataset.FullName as IDatasetName;

            IWorkspaceFactory pWF = new ShapefileWorkspaceFactory();
            IWorkspace pWorkspace = pWF.OpenFromFile(strPath, 0);
            IDataset pDatasetOUT = pWorkspace as IDataset;
            IWorkspaceName pWorkspaceName = pDatasetOUT.FullName as IWorkspaceName;
            IDatasetName pOUTDatasetName = new TableNameClass ();
            pOUTDatasetName.Name = strFilename;
            pOUTDatasetName.WorkspaceName = pWorkspaceName;

            IExportOperation pExpOp = new ExportOperationClass();
            pExpOp.ExportTable(pDatasetName, null, null, pOUTDatasetName, 0);
        }
示例#58
0
        public static void Save(IFeatureClass SourceFeatureClass, string WhereClause, string SaveFilePath)
        {
            IWorkspaceFactory workpsaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace workspace = workpsaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(SaveFilePath), 0);
            var FieldDict = GetFieldDict(SourceFeatureClass);
            IFeatureWorkspace FeatureWorkspace = workspace as IFeatureWorkspace;
            IFeatureClass NewFeatureClass = Create(FeatureWorkspace, System.IO.Path.GetFileNameWithoutExtension(SaveFilePath), esriGeometryType.esriGeometryPolyline, FieldDict);
            Dictionary<string, int> NewIndexDict = GetFieldIndexDict(NewFeatureClass);
            Dictionary<string, int> SourceIndexDict = GetFieldIndexDict(SourceFeatureClass);
            IQueryFilter queryFilter = null;
            if (!string.IsNullOrEmpty(WhereClause))
            {
                queryFilter = new QueryFilterClass();
                queryFilter.WhereClause = WhereClause;
            }
            IFeatureBuffer featureBuffer;
            IFeatureCursor InsertFeatureCursor=null;
            IFeatureCursor SearchfeatureCursor = SourceFeatureClass.Search(queryFilter, false);
            IFeature feature = SearchfeatureCursor.NextFeature();
            while (feature != null)
            {
                featureBuffer = NewFeatureClass.CreateFeatureBuffer();
                InsertFeatureCursor = NewFeatureClass.Insert(true);
                featureBuffer.Shape = feature.Shape;
                foreach (var key in NewIndexDict.Keys)
                {
                    if (SourceIndexDict.ContainsKey(key))
                    {
                        object val = feature.get_Value(SourceIndexDict[key]);
                        if (val!=DBNull.Value)
                        {
                            featureBuffer.set_Value(NewIndexDict[key], val);
                        }

                    }
                }
                InsertFeatureCursor.InsertFeature(featureBuffer);
                InsertFeatureCursor.Flush();
                feature = SearchfeatureCursor.NextFeature();
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(SearchfeatureCursor);
            if (InsertFeatureCursor != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(InsertFeatureCursor);
            }
        }