/// <summary> /// 两图层进行裁剪运算 /// </summary> /// <param name="inputLayer">被裁剪图层</param> /// <param name="clipLayer">裁剪图层</param> /// <param name="outputFullPath">输出图层完整路径</param> public void ClipByLayer(ILayer inputLayer, ILayer clipLayer, string outputFullPath) { string inputPath = GetLayerPath(inputLayer); string clipPath = GetLayerPath(clipLayer); Clip clipTool = new Clip(); clipTool.in_features = inputPath; clipTool.clip_features = clipPath; clipTool.out_feature_class = outputFullPath; Geoprocessor processor = new Geoprocessor(); IGPProcess process = null; processor.OverwriteOutput = true; process = clipTool; processor.Validate(process, true); processor.Execute(process, null); FileInfo fi = new FileInfo(outputFullPath); string pathDir = fi.Directory.FullName; string name = fi.Name; IWorkspaceFactory wsf = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace fws = wsf.OpenFromFile(pathDir, 0) as IFeatureWorkspace; IFeatureClass featCls = fws.OpenFeatureClass(name); IFeatureLayer layer = new FeatureLayerClass(); layer.FeatureClass = featCls; layer.Name = featCls.AliasName; m_mapControl.Map.AddLayer(layer as ILayer); }
public object GetWorkspace(string strType, string strArgs) { IWorkspaceFactory wsf = null; IWorkspace m_SystemWorkspace = null; switch (strType) { case "PGDB": wsf = new AccessWorkspaceFactoryClass(); m_SystemWorkspace = wsf.OpenFromFile(strArgs, 0); break; case "FILEGDB": wsf = new ShapefileWorkspaceFactoryClass(); m_SystemWorkspace = wsf.OpenFromFile(strArgs, 0); break; case "SDE": IPropertySet pSet = new PropertySetClass(); string[] argList = strArgs.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string strArg in argList) { string[] argPair = strArg.Split(new char[] { ':' }); pSet.SetProperty(argPair[0], argPair[1]); } wsf = new SdeWorkspaceFactoryClass(); m_SystemWorkspace = wsf.Open(pSet, 0); break; default: throw new Exception("系统Workspace配置了无法识别的数据库:Workspace类型应该在PGDB、FILEGDB和SDE之内"); } return(m_SystemWorkspace); }
///方法2:用生成等值线方法进行拟合 ///步骤:1)点生成txt文件,存于临时文件夹下; ///2)点文件生成点要素层→转为Raster→提取等值线;《参考生成等值线方法》 #region 制要素 /// <summary> /// 从本地获得要素类 /// </summary> /// <param name="shapefileDirectory">文件路径(不含文件名)</param> /// <param name="shapefileName">文件名</param> /// <returns></returns> /// <remarks></remarks> public static IFeatureClass GetFeatureClassFromShapefileOnDisk(String shapefileDirectory, String shapefileName) { DirectoryInfo directoryInfo_check = new DirectoryInfo(shapefileDirectory); if (directoryInfo_check.Exists) { //检查路径 FileInfo fileInfo_check = new FileInfo(shapefileDirectory + "\\" + shapefileName); if (fileInfo_check.Exists) { //获取要素类 IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(shapefileDirectory, 0); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace; IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(shapefileName); return(featureClass); } else { return(null); } } else { return(null); } }
public void shpDel(string shppath) { if (string.IsNullOrEmpty(shppath)) { return; } if (!System.IO.File.Exists(shppath)) { return; } using (ComReleaser comreleaser = new ComReleaser()) { IWorkspaceFactory WspFac = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace fteWsp = WspFac.OpenFromFile(System.IO.Path.GetDirectoryName(shppath), 0) as IFeatureWorkspace; IFeatureClass fClss = fteWsp.OpenFeatureClass(System.IO.Path.GetFileName(shppath)); IFeatureLayer fteLyr = new FeatureLayerClass(); IDataset dataset = null; if (fClss == null) { return; } fteLyr.FeatureClass = fClss; fteLyr.Name = fteLyr.FeatureClass.AliasName; //定义数据集,保证处于编辑状态 dataset = fteLyr.FeatureClass as IDataset; dataset.Delete(); } }
public void ExportToSHP(string name, string outputPath) { IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace pWorkspace = (IWorkspace)pWorkspaceFactory.OpenFromFile(outputPath, 0); ConvertFeatureClassToGDB(this.m_workSpace, pWorkspace, name, name, null); }
public object GetWorkspace(string strType, string strArgs) { IWorkspaceFactory wsf = null; IWorkspace m_SystemWorkspace = null; switch (strType) { case "PGDB": wsf = new AccessWorkspaceFactoryClass(); m_SystemWorkspace = wsf.OpenFromFile(strArgs, 0); break; case "FILEGDB": wsf = new ShapefileWorkspaceFactoryClass(); m_SystemWorkspace = wsf.OpenFromFile(strArgs, 0); break; case "SDE": IPropertySet pSet = new PropertySetClass(); string[] argList = strArgs.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string strArg in argList) { string[] argPair = strArg.Split(new char[] { ':' }); pSet.SetProperty(argPair[0], argPair[1]); } wsf = new SdeWorkspaceFactoryClass(); m_SystemWorkspace = wsf.Open(pSet, 0); break; default: throw new Exception("系统Workspace配置了无法识别的数据库:Workspace类型应该在PGDB、FILEGDB和SDE之内"); } return m_SystemWorkspace; }
/// <summary> /// Opens a shapefile polyline featureclass /// </summary> /// <returns></returns> private IFeatureClass OpenFeatureClass() { string fileName = System.IO.Path.GetFileNameWithoutExtension(m_shapefileName); //instantiate a new workspace factory IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); //get the workspace directory string path = System.IO.Path.GetDirectoryName(m_shapefileName); //open the workspace containing the featureclass IFeatureWorkspace featureWorkspace = workspaceFactory.OpenFromFile(path, 0) as IFeatureWorkspace; //open the featureclass IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(fileName); //make sure that the featureclass type is polyline if (featureClass.ShapeType != esriGeometryType.esriGeometryPolyline) { featureClass = null; } //return the featureclass return(featureClass); }
/// <summary> /// 打开要素类 /// </summary> /// <param name="path">shp文件的存储路径</param> public static IFeatureClass OpenFeatClass(string path) { if (!File.Exists(path)) { return(null); } IWorkspace workspace; IFeatureWorkspace featureWorkspace; IFeatureClass featureClass; IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); workspace = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(path), 0); featureWorkspace = workspace as IFeatureWorkspace; string filename = System.IO.Path.GetFileNameWithoutExtension(path); featureClass = featureWorkspace.OpenFeatureClass(filename); System.Runtime.InteropServices.Marshal.ReleaseComObject(featureWorkspace); System.Runtime.InteropServices.Marshal.ReleaseComObject(workspaceFactory); if (featureClass != null) { return(featureClass); } return(null); }
//打开shape文件 public static IFeatureClass OpenFeatureClassFromShapefile(string sPath,string sShapeName) { IFeatureClass rltFClass=null; IWorkspaceFactory pWSFact; IWorkspace pWS; IFeatureWorkspace pFWS; try { pWSFact=new ShapefileWorkspaceFactoryClass(); pWS=pWSFact.OpenFromFile(sPath,0); pFWS = pWS as IFeatureWorkspace; rltFClass=pFWS.OpenFeatureClass(sShapeName); } catch(Exception e) { MessageBox.Show(e.Message); return null; } return rltFClass; }
private IFeature Convert_Point2MultiPoint_Class(IFeatureClass PointFeatureClass) { IWorkspaceFactory contourWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace contourFWS = (IFeatureWorkspace)contourWSF.OpenFromFile(workSpaceName, 0); IFields pFields = CreateShapeFields(esriGeometryType.esriGeometryMultipoint); string filename = PointFeatureClass.AliasName + "_muilti"; string filename_shp = workSpaceName + @"/" + filename + ".shp"; if (System.IO.File.Exists(filename_shp)) { System.IO.File.Delete(filename_shp); System.IO.File.Delete(System.IO.Path.ChangeExtension(filename_shp, ".dbf")); System.IO.File.Delete(System.IO.Path.ChangeExtension(filename_shp, ".shx")); } contourFWS.CreateFeatureClass(filename, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass MultiFeatureClass = contourFWS.OpenFeatureClass(filename); IPointCollection pPointCollection = new MultipointClass(); for (int i = 0; i < PointFeatureClass.FeatureCount(null); i++) { IFeature pFeature = PointFeatureClass.GetFeature(i); IPoint pPoint = pFeature.Shape as IPoint; pPointCollection.AddPoint(pPoint); } IFeature MultiFeature = MultiFeatureClass.CreateFeature(); MultiFeature.Shape = pPointCollection as IGeometry; MultiFeature.Store(); return(MultiFeature); }
/// <summary> /// 打开工作空间 /// </summary> /// <param name="dir">目录</param> /// <returns></returns> static public IWorkspace GetShapefileWorkspace(string dir) { IWorkspaceFactory pWsF = new ShapefileWorkspaceFactoryClass(); IWorkspace pWs = pWsF.OpenFromFile(dir, 0); return(pWs); }
public SummaryResultsWindow(Hashtable sumResults) { InitializeComponent(); this._sumResults = sumResults; ShapefileWorkspaceFactoryClass tempWSFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace tempWS = tempWSFactory.OpenFromFile(this._sumResults["workspace"].ToString(), 0); IFeatureWorkspace featureWS = tempWS as IFeatureWorkspace; // Bind dataset to the binding source TableWrapper tableWrapper = new ArcDataBinding.TableWrapper(featureWS.OpenTable(this._sumResults["table"].ToString())); this.SummaryTableGridView.DataSource = tableWrapper; // Create source. BitmapImage bi = new BitmapImage(); // BitmapImage.UriSource must be in a BeginInit/EndInit block. bi.BeginInit(); bi.UriSource = new Uri(this._sumResults["graph"].ToString(), UriKind.RelativeOrAbsolute); bi.EndInit(); // Set the image source. this.SummaryGraph.Width = bi.PixelWidth; this.SummaryGraph.Height = bi.PixelHeight; this.SummaryGraph.Source = bi; }
/// <summary> /// �½���ͼ�� /// </summary> public void CreatePointLayer() { SaveFileDialog sfdPoint = new SaveFileDialog(); sfdPoint.Title = "��ѡ���ͼ��Ĵ洢λ��"; sfdPoint.Filter = "Shapefile(*.shp)|*.shp|All files(*.*)|*.*"; sfdPoint.RestoreDirectory = true; if (sfdPoint.ShowDialog() == DialogResult.OK) { LocalFilePath = sfdPoint.FileName; FilePath = System.IO.Path.GetDirectoryName(LocalFilePath); FileName = System.IO.Path.GetFileName(LocalFilePath); IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = pFields as IFieldsEdit; IField pField = new FieldClass(); IFieldEdit pFieldEdit = pField as IFieldEdit; pFieldEdit.Name_2 = "SHAPE"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef pGeometryDef = new GeometryDefClass(); IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit; pGeometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; pFieldEdit.GeometryDef_2 = pGeometryDef; pFieldsEdit.AddField(pField); IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWorkspace = pWorkspaceFactory.OpenFromFile(FilePath, 0) as IFeatureWorkspace; pFeatureWorkspace.CreateFeatureClass(FileName, pFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", ""); m_mapControl.AddShapeFile(FilePath, FileName); m_mapControl.ActiveView.Refresh(); } }
private void EngineEditingForm_Load(object sender, EventArgs e) { //Set buddy controls axTOCControl1.SetBuddyControl(axMapControl1); axEditorToolbar.SetBuddyControl(axMapControl1); axToolbarControl1.SetBuddyControl(axMapControl1); //Add items to the ToolbarControl axToolbarControl1.AddItem("esriControls.ControlsOpenDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsSaveAsDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsAddDataCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomInTool", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomOutTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapPanTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapFullExtentCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentBackCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentForwardCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); //Add items to the custom editor toolbar axEditorToolbar.AddItem("esriControls.ControlsEditingEditorMenu", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("VertexCommands_CS.VertexCommandsMenu", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconAndText); axEditorToolbar.AddItem("esriControls.ControlsEditingEditTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsEditingSketchTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsUndoCommand", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsRedoCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsEditingTargetToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsEditingTaskToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); //Create a popup menu m_toolbarMenu = new ToolbarMenuClass(); m_toolbarMenu.AddItem("esriControls.ControlsEditingSketchContextMenu", 0, 0, false, esriCommandStyles.esriCommandStyleTextOnly); m_engineEditor = new EngineEditorClass() as IEngineEditSketch; //this class is a singleton //share the command pool axToolbarControl1.CommandPool = axEditorToolbar.CommandPool; m_toolbarMenu.CommandPool = axToolbarControl1.CommandPool; //Create an operation stack for the undo and redo commands to use IOperationStack operationStack = new ControlsOperationStackClass(); axEditorToolbar.OperationStack = operationStack; //add some sample line data to the map IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); //relative file path to the sample data from EXE location string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); filePath = System.IO.Path.Combine(filePath, @"ArcGIS\data\USAMajorHighways"); IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, axMapControl1.hWnd); IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.Name = "Highways"; featureLayer.Visible = true; featureLayer.FeatureClass = workspace.OpenFeatureClass("usa_major_highways"); axMapControl1.Map.AddLayer((ILayer)featureLayer); }
static void SnapPointToClosestPolyline(string shpPath, double x, double y, double tolerance) { string path = Path.GetDirectoryName(shpPath); string name = Path.GetFileNameWithoutExtension(shpPath); _stopWatch.Restart(); IWorkspaceFactory wsf = new ShapefileWorkspaceFactoryClass(); IWorkspace ws = wsf.OpenFromFile(path, 0); IFeatureClass fClass = ((IFeatureWorkspace)ws).OpenFeatureClass(name); _stopWatch.Stop(); DisplayTime(_stopWatch, string.Format("Opening {0}", Path.GetFileName(shpPath))); ISpatialReference sRef = ((IGeoDataset)fClass).SpatialReference; IPoint point = new Point { X = x, Y = y, SpatialReference = sRef }; IFeatureCursor cursor = null; try { IGeometry buffer = ((ITopologicalOperator)point).Buffer(tolerance); ISpatialFilter filter = new SpatialFilter { Geometry = buffer, GeometryField = fClass.ShapeFieldName, SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects }; _stopWatch.Restart(); cursor = fClass.Search(filter, true); _stopWatch.Stop(); DisplayTime(_stopWatch, "Hydrating Cursor"); _stopWatch.Restart(); IFeature feature = cursor.NextFeature(); _stopWatch.Stop(); DisplayTime(_stopWatch, string.Format("...Cursor for 1st record. [Null Row: {0}]", feature == null)); IPoint outPoint = new PointClass(); double distanceAlongurve = 0; double distanceFromCurve = 0; IPolyline6 polyline = (IPolyline6)feature.Shape; bool rightSide = false; polyline.QueryPointAndDistance(esriSegmentExtension.esriNoExtension, point, true, outPoint, ref distanceAlongurve, ref distanceFromCurve, ref rightSide); Marshal.FinalReleaseComObject(outPoint); Marshal.FinalReleaseComObject(polyline); _stopWatch.Restart(); feature = cursor.NextFeature(); _stopWatch.Stop(); DisplayTime(_stopWatch, string.Format("...Cursor for eof. [Null Row: {0}]", feature == null)); } catch (Exception ex) { Console.WriteLine("Exception: {0}", ex.Message); } Marshal.FinalReleaseComObject(cursor); }
private IWorkspace OpenShapfileWorkspace(string ShapeFilePath) { IWorkspace ws = null; IWorkspaceFactory wsf = new ShapefileWorkspaceFactoryClass(); ws = wsf.OpenFromFile(this.ShapeFilePath, 0); return(ws); }
public IFeatureClass CreateShapefile(String sParentDirectory, String sWorkspaceName, String sFileName) { IWorkspaceFactory workspaceFactory; IWorkspace workspace; IFeatureWorkspace featureWorkspace; IFeatureClass featureClass; if (System.IO.Directory.Exists(sParentDirectory + sWorkspaceName)) { workspaceFactory = new ShapefileWorkspaceFactoryClass(); workspace = workspaceFactory.OpenFromFile(sParentDirectory + sWorkspaceName, 0); featureWorkspace = workspace as IFeatureWorkspace; featureClass = featureWorkspace.OpenFeatureClass(sFileName); } else { workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspaceName workspaceName = workspaceFactory.Create(sParentDirectory, sWorkspaceName, null, 0); ESRI.ArcGIS.esriSystem.IName name = workspaceName as ESRI.ArcGIS.esriSystem.IName; workspace = (IWorkspace)name.Open(); featureWorkspace = workspace as IFeatureWorkspace; IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = fields as IFieldsEdit; IFieldEdit fieldEdit = new FieldClass(); fieldEdit.Name_2 = "OID"; fieldEdit.AliasName_2 = "序号"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField((IField)fieldEdit); fieldEdit = new FieldClass(); fieldEdit.Name_2 = "Name"; fieldEdit.AliasName_2 = "名称"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.AddField((IField)fieldEdit); IGeometryDefEdit geoDefEdit = new GeometryDefClass(); ISpatialReference spatialReference = m_map.SpatialReference; geoDefEdit.SpatialReference_2 = spatialReference; geoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; fieldEdit = new FieldClass(); fieldEdit.Name_2 = "Shape"; fieldEdit.AliasName_2 = "形状"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; fieldEdit.GeometryDef_2 = geoDefEdit; fieldsEdit.AddField((IField)fieldEdit); featureClass = featureWorkspace.CreateFeatureClass(sFileName, fields, null, null, esriFeatureType.esriFTSimple, "Shape", ""); if (featureClass == null) { return(null); } } return(featureClass); }
/// <summary> /// 数据预处理程序(按类型删除->添加link字段->删除link) /// <summary> /// <param name="path">shp文件路径</param> /// <param name="strategy">策略(Tree或Stroke)</param> static private void RemoveLink(string inPath, Strategy strategy) { //计时 Stopwatch sw = new Stopwatch(); sw.Start(); string dir = System.IO.Path.GetDirectoryName(inPath); //可以获得不带文件名的路径 string name = System.IO.Path.GetFileNameWithoutExtension(inPath); //可以获得文件名 string linkPath = dir + "\\" + name + "_link.shp"; string spfPath = null; if (strategy == Strategy.Tree) { spfPath = dir + "\\" + name + "_spf.shp"; } else if (strategy == Strategy.Stroke) { spfPath = dir + "\\" + name + "_spf(Stroke).shp"; } Console.WriteLine("linkPath: " + inPath); Console.WriteLine("spfPath: " + spfPath); IFeatureClass spfFeatClass = CopyFeatureClass(linkPath, spfPath); //拷贝要素类 roadTypeIndex = QueryFieldIndex(spfFeatClass, "fclass"); linkIndex = AddField(spfFeatClass, "link", esriFieldType.esriFieldTypeSmallInteger, 1); //打开编辑器 IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(inPath), 0); IWorkspaceEdit workspaceEdit = workspace as IWorkspaceEdit; workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); //删除link道路 if (strategy == Strategy.Tree) { RemoveLinkRoad_Tree(spfFeatClass); } else if (strategy == Strategy.Stroke) { RemoveLinkRoad_Stroke(spfFeatClass); } //停止编辑状态 workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); //停止计时,输出结果 sw.Stop(); int featCount = spfFeatClass.FeatureCount(null); Console.WriteLine("规模:" + spfFeatClass.FeatureCount(null) + " 用时:" + Math.Round(sw.Elapsed.TotalMinutes, 2) + "Min"); }
/// <summary> /// 把DataTable转为ITable ,tempPath 不含文件名的w文件夹路径 /// </summary> /// <param name="mTable"></param> /// <returns></returns> private ITable DataTableToITable(DataTable mTable, string xFieldName, string yFieldName, string tempPath) { try { #region 新建表字段 IField pField = null; IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; fieldsEdit.FieldCount_2 = 2; //添加X字段 pField = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)pField; fieldEdit.Name_2 = "X"; fieldEdit.AliasName_2 = "X"; //设置字段类型 fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldEdit.Editable_2 = true; fieldsEdit.set_Field(0, pField); //添加Y字段 IField pField1 = new FieldClass(); IFieldEdit fieldEdit1 = (IFieldEdit)pField1; fieldEdit1.Name_2 = "Y"; fieldEdit1.AliasName_2 = "Y"; fieldEdit1.Type_2 = esriFieldType.esriFieldTypeDouble; fieldEdit1.Editable_2 = true; fieldsEdit.set_Field(1, pField1); #endregion ShapefileWorkspaceFactoryClass class2 = new ShapefileWorkspaceFactoryClass(); ESRI.ArcGIS.Geodatabase.IWorkspace pWorkspace = class2.OpenFromFile(tempPath, 0); IFeatureWorkspace pFWS = pWorkspace as IFeatureWorkspace; //删除已有的 if (System.IO.File.Exists(tempPath + "点数据.dbf")) { System.IO.File.Delete(tempPath + "点数据.dbf"); } //创建空表 ITable pTable = pFWS.CreateTable("点数据", fieldsEdit, null, null, ""); //遍历DataTable中数据,然后转换为ITable中的数据 int xRowIndex = pTable.Fields.FindField("X"); int yRowIndex = pTable.Fields.FindField("Y"); for (int k = 0; k < mTable.Rows.Count; k++) { //ITable 的记录 IRow row = pTable.CreateRow(); DataRow pRrow = mTable.Rows[k]; row.set_Value(xRowIndex, pRrow[xFieldName]); row.set_Value(yRowIndex, pRrow[yFieldName]); row.Store(); } return(pTable); } catch { return(null); } }
/// <summary> /// /// </summary> /// <returns></returns> public IFeatureClass OpenFeatureClass() { string path2Workspace = Path.GetDirectoryName(FilePath); string shapefileName = Path.GetFileNameWithoutExtension(FilePath); IWorkspaceFactory pWorkspaceFactroy = new ShapefileWorkspaceFactoryClass(); IWorkspace pws = pWorkspaceFactroy.OpenFromFile(path2Workspace, 0); IFeatureWorkspace pFeatureWorkspace = pws as IFeatureWorkspace; return pFeatureWorkspace != null ? pFeatureWorkspace.OpenFeatureClass(shapefileName) : null; }
/// <summary> /// 打开shpfile文件 public IFeatureClass GetFeatureClass(string FilePath, string LayerName) { IWorkspaceFactory pWks = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFwk = pWks.OpenFromFile(FilePath, 0) as IFeatureWorkspace; IFeatureClass pRtClass = pFwk.OpenFeatureClass(LayerName); return(pRtClass); }
private void btnGO_Click(object sender, EventArgs e) { string fileName; string shpFile; int startX, endX; string shpDir; try { if (bDataPath == true) { fileName = txtOutputData.Text; shpDir = fileName.Substring(0, fileName.LastIndexOf("\\")); startX = fileName.LastIndexOf("\\"); endX = fileName.Length; shpFile = fileName.Substring(startX + 1, endX - startX - 1); } else { shpDir = txtOutputData.Text; shpFile = "х╚ох¤▀"; } if (m_pRasterLyr != null) { double dInterval = Convert.ToDouble(txtConInterval.Text); double dBaseLine = Convert.ToDouble(txtBaseLine.Text); object objBaseLine = dBaseLine; ISurfaceOp pRasterSurfaceOp = new RasterSurfaceOpClass(); IRaster pInRaster = m_pRasterLyr.Raster; IFeatureClass pOutFClass = pRasterSurfaceOp.Contour(pInRaster as IGeoDataset, dInterval, ref objBaseLine) as IFeatureClass; //2. QI to IDataset IDataset pFDS = pOutFClass as IDataset; //3. Get a shapefile workspace IWorkspaceFactory pSWF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFWS = pSWF.OpenFromFile(shpDir, 0) as IFeatureWorkspace; //4. Copy contour output to a new shapefile IWorkspace pWS = pFWS as IWorkspace; if (pWS.Exists() == true) { Utility.DelFeatureFile(shpDir, shpFile + ".shp"); } pFDS.Copy(shpFile, pFWS as IWorkspace); IFeatureLayer pFeatLyr = new FeatureLayerClass(); pFeatLyr.FeatureClass = pOutFClass; pFeatLyr.Name = pOutFClass.AliasName; pFeatLyr.Visible = true; pMainFrm.getMapControl().AddLayer(pFeatLyr, 0); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
///<summary> /// 获取shp数值字段列表 /// </summary> /// <param name="inFile">输入shp文件名</param> /// <param name="fields">字段列表</param> public static void GetValueFields(string inFile, List <string> fields) { IWorkspaceFactory pWorkspaceFactory = null; IFeatureWorkspace pFeatureWorkspace = null; IFeatureClass featureClass = null; //IFeatureLayer pFeatureLayer; try { //获取当前路径和文件名 if (inFile == "") { return; } int Index = inFile.LastIndexOf("\\"); string filePath = inFile.Substring(0, Index); string fileName = inFile.Substring(Index + 1); //打开工作空间并获取字段列表 pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(filePath, 0); //pFeatureLayer = new FeatureLayerClass(); featureClass = pFeatureWorkspace.OpenFeatureClass(fileName); int nFields = featureClass.Fields.FieldCount; for (int i = 0; i < nFields; i++) { //if (featureClass.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeDouble || // featureClass.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeInteger || // featureClass.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeSmallInteger) { string name = featureClass.Fields.get_Field(i).Name; fields.Add(name); } } } catch (Exception ex) { throw ex; } finally { if (featureClass != null) { Marshal.ReleaseComObject(featureClass); } if (pFeatureWorkspace != null) { Marshal.ReleaseComObject(pFeatureWorkspace); } if (pWorkspaceFactory != null) { Marshal.ReleaseComObject(pWorkspaceFactory); } } }
//线图层存为shp(未使用)方法3 static void PointToLineShp() { //打开poi的shp文件,设置属性(order) IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pWS = (IFeatureWorkspace)pWSF.OpenFromFile(@"res\poi_shp_jw", 0); IFeatureClass pFeatureclass = pWS.OpenFeatureClass("poi.shp"); IFeatureCursor pCursor = pFeatureclass.Search(null, false); IPolyline pPolyline = new PolylineClass(); IPointCollection pPolycollect = pPolyline as IPointCollection; IDataset dataset = (IDataset)pFeatureclass;//属性表可编辑状态 IWorkspace workspace = dataset.Workspace; IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace; workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); for (int d = 0; d < VerNum; d++) { if (d != startPoiID) { //逐条设置order,生成shp int ss = 0;//节点id int e = 0; while (pCursor != null) { IFeature pFeature = pCursor.NextFeature(); IFields pFields = pFeature.Fields; // IField pField = pFeature.Fields; IClass pClass = pFeatureclass as IClass; if (pFeature != null) { for (e = 0; e < h[ss] + 2; e++) { if (PathRouteTem[d, e] == ss) { return; } } IGeometry pGeometry = pFeature.Shape; object objmiss = Type.Missing; pFeature.set_Value(10, PathRouteTem[d, e]); ss++; } else { pCursor = null; } } } } }
private void ReadShapefileWorksapceFactory(string path) { Wsf = new ShapefileWorkspaceFactoryClass(); Directory = System.IO.Path.GetDirectoryName(path); NameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(path); Extension = System.IO.Path.GetExtension(path); Ws = Wsf.OpenFromFile(Directory, 0); FeatWs = Ws as IFeatureWorkspace; FeatCls = FeatWs.OpenFeatureClass(NameWithoutExtension); EnumDs = Ws.get_Datasets(esriDatasetType.esriDTFeatureClass); }
/// <summary> /// 重写虚态方法 /// 创建PDJBTLocalShapeFile文件 /// </summary> /// <returns></returns> public override bool CreateShapeFile() { bool rbc = false; try { string dir = this.getDir(this.LocalShapePathFileName); string name = this.getFileName(this.LocalShapePathFileName); ShapefileWorkspaceFactoryClass objwsf = new ShapefileWorkspaceFactoryClass(); IWorkspace objws = objwsf.OpenFromFile(dir, 0); IFeatureWorkspace feaureWS = objws as IFeatureWorkspace; IFeatureClass fc = this.CreateFeatureClass(feaureWS, name, esriFeatureType.esriFTSimple, esriGeometryType.esriGeometryPolygon); if (fc != null) { //Add 要素表字段结构(业务字段) IField mField = new FieldClass(); IFieldEdit mFieldEdit = mField as IFieldEdit; mFieldEdit.Name_2 = "PDJB"; mFieldEdit.AliasName_2 = "坡度级别"; mFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; mFieldEdit.Length_2 = 9; fc.AddField(mField); //--SLOPECODE IField fd_slopecode = new FieldClass(); IFieldEdit mfd_slopecode = fd_slopecode as IFieldEdit; mfd_slopecode.Name_2 = "SLOPECODE"; mfd_slopecode.AliasName_2 = "坡度代码"; mfd_slopecode.Type_2 = esriFieldType.esriFieldTypeInteger; mfd_slopecode.Length_2 = 1; fc.AddField(fd_slopecode); //-- fc = null; // rbc = true; } feaureWS = null; objws = null; objwsf = null; } catch { rbc = false; } return(rbc); }
/// <summary> /// 计算绿地率 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { string file_path1 = myCol[comboBox1.Text]; string file_path2 = myCol[comboBox2.Text]; string strShapeFolder = System.IO.Path.GetDirectoryName(file_path1); string filename1 = System.IO.Path.GetFileName(file_path1); string filename2 = System.IO.Path.GetFileName(file_path2); IWorkspaceFactory pWSF = null; double groundArea = 0; double greenLand = 0; double greenRatio = 0; try { pWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pWS = pWSF.OpenFromFile(@strShapeFolder, 0) as IFeatureWorkspace; IFeatureClass pFC1 = pWS.OpenFeatureClass(filename1); IFeatureClass pFC2 = pWS.OpenFeatureClass(filename2); IFeatureCursor pFeatureCur1 = pFC1.Search(null, false); IFeature pFeature1 = pFeatureCur1.NextFeature(); while (pFeature1 != null) { if (pFeature1.Shape.GeometryType == esriGeometryType.esriGeometryPolygon) { IArea pArea = pFeature1.Shape as IArea; groundArea = groundArea + pArea.Area; } pFeature1 = pFeatureCur1.NextFeature(); } IFeatureCursor pFeatureCur2 = pFC2.Search(null, false); IFeature pFeature2 = pFeatureCur2.NextFeature(); while (pFeature2 != null) { if (pFeature2.Shape.GeometryType == esriGeometryType.esriGeometryPolygon) { IArea pArea = pFeature2.Shape as IArea; greenLand = greenLand + pArea.Area; } pFeature2 = pFeatureCur2.NextFeature(); } greenRatio = greenLand / groundArea * 100; label3.Text = greenRatio.ToString("#0.00") + "%"; } catch (System.Exception ex) { MessageBox.Show("计算失败!"); } }
public void SolveRoute() { IWorkspaceFactory factory = new ShapefileWorkspaceFactoryClass(); this.m_pWorkspace = factory.OpenFromFile(this.SHAPE_WORKSPACE, 0); this.SetMemberVariables(); this.Solve(); this.m_pWorkspace = null; this.m_pNetworkDataset = null; this.m_pInputStopsFClass = null; }
private IWorkspace OpenShapfileWorkspace(string ShapeFilePath) { IWorkspace ws = null; IWorkspaceFactory wsf = new ShapefileWorkspaceFactoryClass(); //using DataSourcesFile if (ShapeFilePath != null) { ws = wsf.OpenFromFile(ShapeFilePath, 0); } return(ws); }
/// <summary> /// /// </summary> /// <returns></returns> public IFeatureClass OpenFeatureClass() { string path2Workspace = Path.GetDirectoryName(FilePath); string shapefileName = Path.GetFileNameWithoutExtension(FilePath); IWorkspaceFactory pWorkspaceFactroy = new ShapefileWorkspaceFactoryClass(); IWorkspace pws = pWorkspaceFactroy.OpenFromFile(path2Workspace, 0); IFeatureWorkspace pFeatureWorkspace = pws as IFeatureWorkspace; return(pFeatureWorkspace != null? pFeatureWorkspace.OpenFeatureClass(shapefileName) : null); }
//---- private void RefreshSpatialReferenceText(string file) { this.textBox3.Text = ""; try { //首先获取文件名,文件路径及文件类型 string[] sArray = file.Split('\\'); string filename = sArray[sArray.Length - 1]; string url = ""; for (int i = 0; i < sArray.Length - 1; i++) { url = url + sArray[i] + "\\"; } string[] sFile = filename.Split('.'); string file_ext = ""; if (sFile.Length > 0) { file_ext = sFile[sFile.Length - 1]; } file_ext = file_ext.ToLower(); //---- ShapefileWorkspaceFactoryClass wsf = new ShapefileWorkspaceFactoryClass(); IWorkspace ws = wsf.OpenFromFile(url, 0); IFeatureWorkspace pFeatureWorkspace; pFeatureWorkspace = (IFeatureWorkspace)ws; IFeatureClass pFeatureClass = null; pFeatureClass = pFeatureWorkspace.OpenFeatureClass(filename); this.RefreshSpatialReferenceText(pFeatureClass); ZhFeatureClass zhfeaclass = new ZhPolygonFeatureClass(pFeatureClass); List <string> FieldNames = zhfeaclass.GetFieldNames(); this.CB_Fields.Items.Clear(); foreach (string fn in FieldNames) { this.CB_Fields.Items.Add(fn); } TokayWorkspace.ComRelease(pFeatureClass); pFeatureClass = null; TokayWorkspace.ComRelease(ws); ws = null; wsf = null; } catch (Exception ee) { this.textBox3.Text = ""; MessageBox.Show(ee.Message, "选择文件提示"); } }
public void CreateLineShpFile(string fileName, ISpatialReference pSRF) { //判断需要生成的线文件是否存在,若不存在则创建文件,若存在则将新添加的线写入文件 if (File.Exists(fileName)) { MessageBox.Show("file already exist, please change file name!"); return; } else { string pLineFile = fileName; string pFilePath = System.IO.Path.GetDirectoryName(pLineFile); string pFileName = System.IO.Path.GetFileName(pLineFile); //打开工作空间 IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pWS = (IFeatureWorkspace)pWSF.OpenFromFile(pFilePath, 0); //判断文件是否存在,若不存在则创建文件 if (!(File.Exists(fileName))) { const string strShapeFieldName = "shape"; //设置字段集 IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields; //设置字段 IField pField = new FieldClass(); IFieldEdit pFieldEdit = (IFieldEdit)pField; //创建类型为几何类型的字段 pFieldEdit.Name_2 = strShapeFieldName; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; //为esriFieldTypeGeometry类型的字段创建几何定义,包括类型和空间参照 IGeometryDef pGeoDef = new GeometryDefClass(); //The geometry definition for the field if IsGeometry is TRUE. IGeometryDefEdit pGeoDefEdit = (IGeometryDefEdit)pGeoDef; pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; pGeoDefEdit.SpatialReference_2 = pSRF; pFieldEdit.GeometryDef_2 = pGeoDef; pFieldsEdit.AddField(pField); //add length field pField = new FieldClass(); pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "length"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; pFieldEdit.IsNullable_2 = true; pFieldsEdit.AddField(pField); //创建shapefile线图层 pWS.CreateFeatureClass(pFileName, pFields, null, null, esriFeatureType.esriFTSimple, strShapeFieldName, ""); } } }
private void button2_Click(object sender, EventArgs e) { //工作空间 IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWorkspace = pWorkspaceFactory.OpenFromFile(pFilePath, 0) as IFeatureWorkspace; //创建字段集2 IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); //创建必要字段 IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; //必要字段 IFields pFields = new FieldsClass(); pFields = ocDescription.RequiredFields; //要素类的几何类型、坐标系 int shapeFileIndex = pFields.FindField(fcDescription.ShapeFieldName); IField pField = pFields.get_Field(shapeFileIndex); IGeometryDef pGeometryDef = pField.GeometryDef; IGeometryDefEdit pGeometryDefEdit = (IGeometryDefEdit)pGeometryDef; pGeometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironmentClass(); //更改为可选的坐标系 IProjectedCoordinateSystem pProjectedCoordinateSystem = pSpatialReferenceFactory.CreateProjectedCoordinateSystem( (int)esriSRProjCS4Type.esriSRProjCS_Xian1980_GK_Zone_21); pGeometryDefEdit.SpatialReference_2 = pProjectedCoordinateSystem; //自定义字段 IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields; addField(pFieldsEdit, "FID"); addField(pFieldsEdit, "Row"); addField(pFieldsEdit, "Column"); addField(pFieldsEdit, "Number"); //传入字段 IFieldChecker pFieldChecker = new FieldCheckerClass(); IEnumFieldError pEnumFieldError = null; IFields validatedFields = null; pFieldChecker.ValidateWorkspace = (IWorkspace)pFeatureWorkspace; pFieldChecker.Validate(pFields, out pEnumFieldError, out validatedFields); //创建要素类 IFeatureClass pFeatureClass = pFeatureWorkspace.CreateFeatureClass(pFileName, validatedFields , ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); MessageBox.Show("创建要素类成功"); }
public IWorkspace OpenWorkspace(string strGDBName) { IWorkspace pWorkSpace; IWorkspaceFactory pWorkspaceFactory=new ShapefileWorkspaceFactoryClass(); pWorkSpace=pWorkspaceFactory.OpenFromFile(strGDBName,0); return pWorkSpace; }
/// <summary> /// 执行栅格转矢量 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RtoF_backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; //设置CancellationPending可以退出任务线程 if (worker.CancellationPending == true) { e.Cancel = true; } else { try { FileInfo inputfinfo = new FileInfo(rastertofeature_input.Text); FileInfo outputinfo = new FileInfo(rastertofeature_output.Text); IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(outputinfo.DirectoryName, 0);//创建输出工作空间 IWorkspaceFactory workspacefactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterworkspace = workspacefactory.OpenFromFile(inputfinfo.DirectoryName, 0) as IRasterWorkspace; IRasterDataset rasterdataset = rasterworkspace.OpenRasterDataset(inputfinfo.Name); IGeoDataset geodataset = rasterdataset as IGeoDataset; watch = new Stopwatch(); watch.Start(); //执行转换 IConversionOp conversionOp = new RasterConversionOpClass(); IGeoDataset geodatasetresult = null; if (rastertofeature_geometry.Text == "POINT") { geodatasetresult = conversionOp.ToFeatureData(geodataset, esriGeometryType.esriGeometryPoint, workspace, outputinfo.Name); } else { if (rastertofeature_geometry.Text == "POLYLINE") { geodatasetresult = conversionOp.ToFeatureData(geodataset, esriGeometryType.esriGeometryPolyline, workspace, outputinfo.Name); } else { geodatasetresult = conversionOp.ToFeatureData(geodataset, esriGeometryType.esriGeometryPolygon, workspace, outputinfo.Name); } } } catch (Exception erro) { MessageBox.Show(erro.Message, "错误"); } } }
private void btnGO_Click(object sender, EventArgs e) { string fileName; string shpFile; int startX, endX; string shpDir; try { if (bDataPath == true) { fileName=txtOutputData.Text; shpDir =fileName.Substring(0, fileName.LastIndexOf("\\")); startX=fileName.LastIndexOf("\\"); endX=fileName.Length; shpFile=fileName.Substring(startX+1,endX-startX-1); } else { shpDir=txtOutputData.Text; shpFile="��ֵ��"; } if (m_pRasterLyr != null) { double dInterval=Convert.ToDouble(txtConInterval.Text); double dBaseLine=Convert.ToDouble(txtBaseLine.Text); object objBaseLine=dBaseLine; ISurfaceOp pRasterSurfaceOp = new RasterSurfaceOpClass(); IRaster pInRaster = m_pRasterLyr.Raster; IFeatureClass pOutFClass= pRasterSurfaceOp.Contour(pInRaster as IGeoDataset , dInterval, ref objBaseLine) as IFeatureClass ; //2. QI to IDataset IDataset pFDS=pOutFClass as IDataset ; //3. Get a shapefile workspace IWorkspaceFactory pSWF=new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFWS=pSWF.OpenFromFile(shpDir,0) as IFeatureWorkspace ; //4. Copy contour output to a new shapefile IWorkspace pWS = pFWS as IWorkspace; if (pWS.Exists() == true) Utility.DelFeatureFile(shpDir, shpFile + ".shp"); pFDS.Copy(shpFile,pFWS as IWorkspace ); IFeatureLayer pFeatLyr = new FeatureLayerClass(); pFeatLyr.FeatureClass = pOutFClass; pFeatLyr.Name = pOutFClass.AliasName; pFeatLyr.Visible = true; pMainFrm.getMapControl().AddLayer(pFeatLyr, 0); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private IFeatureLayer CreateShpFromPoints(List <CPoint> cPointList, string filePath) { int index = filePath.LastIndexOf('\\'); string folder = filePath.Substring(0, index); string shapeName = filePath.Substring(index + 1); IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFWS = (IFeatureWorkspace)pWSF.OpenFromFile(folder, 0); IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit; pFieldsEdit = (IFieldsEdit)pFields; IField pField = new FieldClass(); IFieldEdit pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "Shape"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef pGeometryDef = new GeometryDefClass(); IGeometryDefEdit pGDefEdit = (IGeometryDefEdit)pGeometryDef; pGDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; //定义坐标系 ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass(); ISpatialReference pSpatialReference = pSRF.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_Beijing1954); pGDefEdit.SpatialReference_2 = pSpatialReference; pFieldEdit.GeometryDef_2 = pGeometryDef; pFieldsEdit.AddField(pField); IFeatureClass pFeatureClass; pFeatureClass = pFWS.CreateFeatureClass(shapeName, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", ""); IPoint pPoint = new PointClass(); for (int j = 0; j < cPointList.Count; j++) { pPoint.X = cPointList[j].X; pPoint.Y = cPointList[j].Y; IFeature pFeature = pFeatureClass.CreateFeature(); pFeature.Shape = pPoint; pFeature.Store(); } IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.Name = shapeName; pFeatureLayer.FeatureClass = pFeatureClass; return(pFeatureLayer); }
private void MainForm_Load(object sender, EventArgs e) { m_mapControl = (IMapControl3) axMapControl1.Object; //relative file path to the sample data from EXE location string filePath = @"..\..\..\data\USAMajorHighways"; //Add Lakes layer IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, axMapControl1.hWnd); IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.Name = "Lakes"; featureLayer.Visible = true; featureLayer.FeatureClass = workspace.OpenFeatureClass("us_lakes"); #region create a SimplerRenderer IRgbColor color = new RgbColorClass(); color.Red = 190; color.Green = 232; color.Blue = 255; ISimpleFillSymbol sym = new SimpleFillSymbolClass(); sym.Color = color; ISimpleRenderer renderer = new SimpleRendererClass(); renderer.Symbol = sym as ISymbol; #endregion ((IGeoFeatureLayer)featureLayer).Renderer = renderer as IFeatureRenderer; axMapControl1.Map.AddLayer((ILayer)featureLayer); //Add Highways layer featureLayer = new FeatureLayerClass(); featureLayer.Name = "Highways"; featureLayer.Visible = true; featureLayer.FeatureClass = workspace.OpenFeatureClass("usa_major_highways"); axMapControl1.Map.AddLayer((ILayer)featureLayer); //******** Important ************* //store a reference to this form (Mainform) using the EditHelper class EditHelper.TheMainForm = this; EditHelper.IsEditorFormOpen = false; //add the EditCmd command to the toolbar axEditorToolbar.AddItem("esriControls.ControlsOpenDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsSaveAsDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsAddDataCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem(new EditCmd(), 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); }
/// <summary> /// 打开Workspace /// </summary> /// <param name="wsType"></param> /// <param name="objWorkspace">当为SDE时使用IPropertySet,其余情况使用路径(string)</param> /// <returns></returns> public static IWorkspace OpenWorkspace(enumWorkspaceType wsType, object objWorkspace) { IWorkspaceFactory wsf = null; try { switch (wsType) { case enumWorkspaceType.FileGDB: wsf = new FileGDBWorkspaceFactoryClass(); return wsf.OpenFromFile(objWorkspace as string, 0); case enumWorkspaceType.PGDB: wsf = new AccessWorkspaceFactoryClass(); return wsf.OpenFromFile(objWorkspace as string, 0); case enumWorkspaceType.File: wsf = new ShapefileWorkspaceFactoryClass(); return wsf.OpenFromFile(objWorkspace as string, 0); case enumWorkspaceType.SDE: wsf = new SdeWorkspaceFactoryClass(); IPropertySet pSet = objWorkspace as IPropertySet; if (pSet == null) { string strArgs = objWorkspace as string; pSet = new PropertySetClass(); string[] argList = strArgs.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string strArg in argList) { string[] argPair = strArg.Split(new char[] { '=' }); pSet.SetProperty(argPair[0], argPair[1]); } } return wsf.Open(pSet, 0); } } catch { return null; } finally { if (wsf != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(wsf); } return null; }
private void addFiled(string path) { this.comboBox2.Items.Clear(); this.comboBox3.Items.Clear(); IWorkspaceFactory m_workspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace featureWorkspce = m_workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(path), 0) as IFeatureWorkspace; m_fc = featureWorkspce.OpenFeatureClass(System.IO.Path.GetFileName(path)); IFields pFields = m_fc.Fields; for (int i = 0; i < pFields.FieldCount; i++) { this.comboBox2.Items.Add(pFields.get_Field(i).Name); this.comboBox3.Items.Add(pFields.get_Field(i).Name); } }
public void Run() { IWorkspaceFactory shapefileworkspaceF = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = shapefileworkspaceF.OpenFromFile(workspaceName, 0); IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; IFeatureClass pFeatureClass = featureWorkspace.OpenFeatureClass(shapefileName) as IFeatureClass; ISpatialReference pSpatialref = new UnknownCoordinateSystemClass(); for (int i = 0; i < pFeatureClass.FeatureCount(null); i++) { IFeature pFeature = (IFeature)pFeatureClass.GetFeature(i); pFeature.Shape.SpatialReference = pSpatialref; pFeature.Store(); } }
private void EngineEditingForm_Load(object sender, EventArgs e) { //Set buddy controls axTOCControl1.SetBuddyControl(axMapControl1); axEditorToolbar.SetBuddyControl(axMapControl1); axToolbarControl1.SetBuddyControl(axMapControl1); //Add items to the ToolbarControl axToolbarControl1.AddItem("esriControls.ControlsOpenDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsSaveAsDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsAddDataCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomInTool", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomOutTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapPanTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapFullExtentCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentBackCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentForwardCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); //Add items to the custom editor toolbar axEditorToolbar.AddItem("esriControls.ControlsEditingEditorMenu", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsEditingEditTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsEditingSketchTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsUndoCommand", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsRedoCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsEditingTargetToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axEditorToolbar.AddItem("esriControls.ControlsEditingTaskToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); //Create a popup menu m_toolbarMenu = new ToolbarMenuClass(); m_toolbarMenu.AddItem("esriControls.ControlsEditingSketchContextMenu", 0, 0, false, esriCommandStyles.esriCommandStyleTextOnly); //share the command pool axToolbarControl1.CommandPool = axEditorToolbar.CommandPool; m_toolbarMenu.CommandPool = axEditorToolbar.CommandPool; //Create an operation stack for the undo and redo commands to use IOperationStack operationStack = new ControlsOperationStackClass(); axEditorToolbar.OperationStack = operationStack; //add some sample line data to the map IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); //relative file path to the sample data from EXE location string filePath = @"..\..\..\..\data\USAMajorHighways"; IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, axMapControl1.hWnd); IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.Name = "Highways"; featureLayer.Visible = true; featureLayer.FeatureClass = workspace.OpenFeatureClass("usa_major_highways"); axMapControl1.Map.AddLayer((ILayer)featureLayer); }
/// <summary> /// 储存点shp,聚类号在"index"字段中标注 /// </summary> public void CreatePointsShapefile() { string filePath = m_dataInfo.GetOutputFilePath(); string fileName = m_dataInfo.GetOutputFileName(); ISpatialReference spatialReference = m_dataInfo.GetSpatialReference(); int index = fileName.LastIndexOf("."); fileName = fileName.Substring(0, index); fileName = fileName + "_pts.shp"; //打开工作空间 const string strShapeFieldName = "shape"; IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pWS = (IFeatureWorkspace)pWSF.OpenFromFile(filePath, 0); //设置字段集 IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields; //设置字段 IField pField = new FieldClass(); IFieldEdit pFieldEdit = (IFieldEdit)pField; //创建类型为几何类型的字段 pFieldEdit.Name_2 = strShapeFieldName; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; //为esriFieldTypeGeometry类型的字段创建几何定义,包括类型和空间参照 IGeometryDef pGeoDef = new GeometryDefClass(); //The geometry definition for the field if IsGeometry is TRUE. IGeometryDefEdit pGeoDefEdit = (IGeometryDefEdit)pGeoDef; pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; pGeoDefEdit.SpatialReference_2 = spatialReference; pFieldEdit.GeometryDef_2 = pGeoDef; pFieldsEdit.AddField(pField); pField = new FieldClass(); pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "index"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; pFieldEdit.Precision_2 = 7;//数值精度 // pFieldEdit.Scale_2 = 3;//小数点位数 pFieldsEdit.AddField(pField); //创建shapefile pWS.CreateFeatureClass(fileName, pFields, null, null, esriFeatureType.esriFTSimple, strShapeFieldName, ""); //在featureclass中创建feature IWorkspaceEdit workspaceEdit = pWS as IWorkspaceEdit; workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); IFeatureClass featureClass = pWS.OpenFeatureClass(fileName); IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer(); IFeatureCursor featureCursor = featureClass.Search(null, true); IFeature feature = featureCursor.NextFeature(); while (feature != null) { feature.Delete(); feature = featureCursor.NextFeature(); } featureCursor = featureClass.Insert(true); int typeFieldIndex = featureClass.FindField("index"); //插入点,并写入聚类号 for (int i = 0; i < m_clusters.GetClusterCount(); i++) { Cluster currentCluster = m_clusters.GetCluster(i); List<IPoint> currentPoints = currentCluster.GetPointsList(); for (int j = 0; j < currentPoints.Count; j++) { featureBuffer.set_Value(typeFieldIndex, currentCluster.GetClusterIndex()); featureBuffer.Shape = currentPoints[j] as IGeometry; object featureOID = featureCursor.InsertFeature(featureBuffer); } } featureCursor.Flush(); workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor); //将新创建的shapfile作为图层添加到map里 IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.FeatureClass = featureClass; featureLayer.Name = featureClass.AliasName; m_pointLayer = featureLayer; ////设置渲染 //DefinePointUniqueValueRenderer(featureLayer as IGeoFeatureLayer, "Class"); //m_mapControl.AddLayer(featureLayer as ILayer); //this.m_mapControl.Refresh(); }
/// <summary> /// 储存凸包shp,聚类号在"index"字段中标注 /// </summary> public void CreatePolygonShapefile() { string filePath = m_dataInfo.GetOutputFilePath(); string fileName = m_dataInfo.GetOutputFileName(); ISpatialReference spatialReference = m_dataInfo.GetSpatialReference(); //打开工作空间 const string strShapeFieldName = "shape"; IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pWS = (IFeatureWorkspace)pWSF.OpenFromFile(filePath, 0); //设置字段集 IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields; //设置字段 IField pField = new FieldClass(); IFieldEdit pFieldEdit = (IFieldEdit)pField; //创建类型为几何类型的字段 pFieldEdit.Name_2 = strShapeFieldName; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; //为esriFieldTypeGeometry类型的字段创建几何定义,包括类型和空间参照 IGeometryDef pGeoDef = new GeometryDefClass(); //The geometry definition for the field if IsGeometry is TRUE. IGeometryDefEdit pGeoDefEdit = (IGeometryDefEdit)pGeoDef; pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; pGeoDefEdit.SpatialReference_2 = spatialReference; pFieldEdit.GeometryDef_2 = pGeoDef; pFieldsEdit.AddField(pField); pField = new FieldClass(); pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "index"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; pFieldEdit.Precision_2 = 7;//数值精度 pFieldsEdit.AddField(pField); //创建shapefile pWS.CreateFeatureClass(fileName, pFields, null, null, esriFeatureType.esriFTSimple, strShapeFieldName, ""); //在featureclass中创建feature IWorkspaceEdit workspaceEdit = pWS as IWorkspaceEdit; workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); IFeatureClass featureClass = pWS.OpenFeatureClass(fileName); IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer(); IFeatureCursor featureCursor = featureClass.Search(null, true); IFeature feature = featureCursor.NextFeature(); while (feature != null) { feature.Delete(); feature = featureCursor.NextFeature(); } featureCursor = featureClass.Insert(true); int typeFieldIndex = featureClass.FindField("index"); for (int i = 0; i < m_clusters.GetClusterCount(); i++) { Cluster currentCluster = m_clusters.GetCluster(i); IPolygon currentPolygon = currentCluster.GetConvexHull(); //we know that there are IPoints only in the Geometrycollection. //But this is the safe and recommended way if (currentPolygon != null) { featureBuffer.set_Value(typeFieldIndex, currentCluster.GetClusterIndex()); featureBuffer.Shape = currentPolygon as IGeometry; object featureOID = featureCursor.InsertFeature(featureBuffer); } } featureCursor.Flush(); workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor); //将新创建的shapfile作为图层添加到map里 IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.FeatureClass = featureClass; featureLayer.Name = featureClass.AliasName; m_polygonLayer = featureLayer; /* //提前设置渲染 DefinePolygonUniqueValueRenderer(featureLayer as IGeoFeatureLayer, "ClusterIndex"); m_mapControl.AddLayer(featureLayer as ILayer); this.m_mapControl.Refresh(); */ }
private void btnGO_Click(object sender, EventArgs e) { string fileName; string shpFile; int startX, endX; string shpDir; object Missing = Type.Missing; //if (bFeatDataPath == true) //{ // fileName = comboBoxInData.Text; // shpDir = fileName.Substring(0, fileName.LastIndexOf("\\")); // startX = fileName.LastIndexOf("\\"); // endX = fileName.Length; // shpFile = fileName.Substring(startX + 1, endX - startX - 1); // pFClass = Utility.OpenFeatureClassFromShapefile(shpDir, shpFile); //} //else //{ // pFClass = GetFeatureFromMapLyr(comboBoxInData.Text); //} if (bRasterDataPath == true) { fileName = txtOutPath.Text; shpDir = fileName.Substring(0, fileName.LastIndexOf("\\")); startX = fileName.LastIndexOf("\\"); endX = fileName.Length; shpFile = fileName.Substring(startX + 1, endX - startX - 1); } else { shpDir = txtOutPath.Text; shpFile = "դ��ת����"; } try { //ɾ����ʱ�����ļ� DelFeatFile(shpDir, shpFile); //���դ�����ݼ� IRasterDescriptor pRsDescriptor = new RasterDescriptorClass(); pRsDescriptor.Create(m_pInRaster, new QueryFilterClass(), comboBoxField.Text); //�����������ռ� IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IWorkspace pWS = pWSF.OpenFromFile(shpDir, 0); //ת��դ��Ϊ������ IConversionOp pConversionOp = new RasterConversionOpClass(); IFeatureClass pOutFeatCls = null; switch (comboBoxGeomeryType.Text) { case "��": pOutFeatCls = pConversionOp.RasterDataToPointFeatureData(pRsDescriptor as IGeoDataset, pWS, shpFile) as IFeatureClass; break; case "��": pOutFeatCls = pConversionOp.RasterDataToLineFeatureData(pRsDescriptor as IGeoDataset, pWS, shpFile, false, false, ref Missing) as IFeatureClass; break; case "��": pOutFeatCls = pConversionOp.RasterDataToPolygonFeatureData(pRsDescriptor as IGeoDataset, pWS, shpFile, false) as IFeatureClass; break; } IFeatureLayer pFeatLyr = new FeatureLayerClass(); pFeatLyr.FeatureClass = pOutFeatCls; pMap.AddLayer(pFeatLyr); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
// //ɾ���Ѵ��ڵ������ļ� // private void DelFeatFile(string sPath, string sName) { try { IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFeatWorkspace = pWorkspaceFactory.OpenFromFile(sPath, 0) as IFeatureWorkspace; IFeatureClass pFeatCls = pFeatWorkspace.OpenFeatureClass(sName); IDataset pDataset = pFeatCls as IDataset; pDataset.Delete(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private static string GetSpatialReference(string shapeFilePath) { var workspaceFactory = new ShapefileWorkspaceFactoryClass(); var featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(Path.GetDirectoryName(shapeFilePath), 0); var featureClass = featureWorkspace.OpenFeatureClass(Path.GetFileNameWithoutExtension(shapeFilePath)); ISpatialReference spatialReference = null; if (featureClass != null) { IGeoDataset geoDataset = featureClass as IGeoDataset; spatialReference = geoDataset.SpatialReference; return "EPSG:"+spatialReference.FactoryCode; } return string.Empty; }
/// <summary> /// Get the FeatureClass from a Shapefile on disk (hard drive). /// </summary> /// <param name="string_ShapefileDirectory">A System.String that is the directory where the shapefile is located. Example: "C:\data\USA"</param> /// <param name="string_ShapefileName">A System.String that is the shapefile name. Note: the shapefile extension's (.shp, .shx, .dbf, etc.) is not provided! Example: "States"</param> /// <returns>An IFeatureClass interface. Nothing (VB.NET) or null (C#) is returned if unsuccessful.</returns> /// <remarks></remarks> public IFeatureClass GetFeatureClassFromShapefileOnDisk(System.String string_ShapefileDirectory, System.String string_ShapefileName) { System.IO.DirectoryInfo directoryInfo_check = new System.IO.DirectoryInfo(string_ShapefileDirectory); if (directoryInfo_check.Exists) { //We have a valid directory, proceed System.IO.FileInfo fileInfo_check = new System.IO.FileInfo(string_ShapefileDirectory + "\\" + string_ShapefileName + ".shp"); if (fileInfo_check.Exists) { //We have a valid shapefile, proceed IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(string_ShapefileDirectory, 0); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace; // Explict Cast IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(string_ShapefileName); return featureClass; } else { //Not valid shapefile return null; } } else { // Not valid directory return null; } }
// // // public static void createShapeFile(String folderName, String shapeName) { if (folderName == "" || shapeName == "") return; string shapeFieldName = "shape"; try { IFeatureWorkspace pFWS = null; IWorkspaceFactory pWorkspaceFactory = null; pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); //if(pWorkspaceFactory.IsWorkspace(folderName)==false) return; pFWS = pWorkspaceFactory.OpenFromFile(folderName, 0) as IFeatureWorkspace; IFields pFields = null; IFieldsEdit pFieldsEdit = null; pFields = new FieldsClass(); pFieldsEdit = pFields as IFieldsEdit; IField pField = null; IFieldEdit pFieldEdit = null; //Make the shape field it will need a geometry definition, with a spatial reference pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.Name_2 = shapeFieldName; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef pGeomDef = null; IGeometryDefEdit pGeomDefEdit = null; pGeomDef = new GeometryDefClass(); pGeomDefEdit = pGeomDef as IGeometryDefEdit; pGeomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; pGeomDefEdit.SpatialReference_2 = new UnknownCoordinateSystemClass(); pFieldEdit.GeometryDef_2 = pGeomDefEdit; pFieldsEdit.AddField(pField); //Add another miscellaneous text field pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.Length_2 = 30; pFieldEdit.Name_2 = "TextField"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; pFieldsEdit.AddField(pField); IFeatureClass pFeatClass = null; pFeatClass = pFWS.CreateFeatureClass(shapeName, pFields, null, null, esriFeatureType.esriFTSimple, shapeFieldName, ""); MessageBox.Show("��Ϊ" + shapeName + "��shape�ļ������ɹ�"); } catch (Exception e) { MessageBox.Show(e.Message); } }
//����DBASE�ļ� public static ITable CreateDBFTable(string strName, string strFolder, bool overwrite, IFields pFields) { IFeatureWorkspace pFWS = null; IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); DirectoryInfo dir = new DirectoryInfo(strFolder); FileInfo fileInfo = new FileInfo(strFolder + @"\" + strName + ".dbf"); if (dir.Exists) pFWS = pWSF.OpenFromFile(strFolder, 0) as IFeatureWorkspace; if (fileInfo.Exists) { if (overwrite) fileInfo.Delete(); else { fileInfo.Delete(); } } IFieldsEdit pFieldsEdit; //����ֶμ��ϲ��ܴ��ڣ����� if (pFields == null) { pFields = new FieldsClass(); pFieldsEdit = pFields as IFieldsEdit; pFieldsEdit.FieldCount_2 = 1; IField pField = new FieldClass(); IFieldEdit pFieldEdit = pField as IFieldEdit; pFieldEdit.Length_2 = 30; pFieldEdit.Name_2 = "TextField"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; pFieldEdit.AliasName_2 = "hi"; pFieldsEdit.set_Field(0, pField); } ITable pTable = pFWS.CreateTable(strName, pFields, null, null, ""); return pTable; }
public static IWorkspace GetShapefileWorkspace(string sFilePath) { if (!File.Exists(sFilePath)) { return null; } try { IWorkspaceFactory factory = new ShapefileWorkspaceFactoryClass(); sFilePath = System.IO.Path.GetDirectoryName(sFilePath); return factory.OpenFromFile(sFilePath, 0); } catch { return null; } }
private IFeatureClass loadShapfile() { IWorkspaceFactory pWsFact = new ShapefileWorkspaceFactoryClass(); IWorkspace pWs = pWsFact.OpenFromFile(m_Dirpath, 0); IFeatureWorkspace pFeaWs = pWs as IFeatureWorkspace; IFeatureClass pFeaCls = pFeaWs.OpenFeatureClass(m_Filename); return pFeaCls; }
/// <summary> /// Load the information from the MajorCities featureclass to the locations table /// </summary> private void PopulateLocationsTableProc() { //get the ArcGIS path from the registry RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\ESRI\ArcObjectsSdk10.4"); string path = Convert.ToString(key.GetValue("InstallDir")); if (!System.IO.File.Exists(System.IO.Path.Combine(path, @"Samples\Data\USZipCodeData\ZipCode_Boundaries_US_Major_Cities.shp"))) { MessageBox.Show("Cannot find file ZipCode_Boundaries_US_Major_Cities.shp!"); return; } //open the featureclass IWorkspaceFactory wf = new ShapefileWorkspaceFactoryClass() as IWorkspaceFactory; IWorkspace ws = wf.OpenFromFile(System.IO.Path.Combine(path, @"Samples\Data\USZipCodeData"), 0); IFeatureWorkspace fw = ws as IFeatureWorkspace; IFeatureClass featureClass = fw.OpenFeatureClass("ZipCode_Boundaries_US_Major_Cities"); //map the name and zip fields int zipIndex = featureClass.FindField("ZIP"); int nameIndex = featureClass.FindField("NAME"); string cityName; long zip; try { //iterate through the features and add the information to the table IFeatureCursor fCursor = null; fCursor = featureClass.Search(null, true); IFeature feature = fCursor.NextFeature(); int index = 0; while(null != feature) { object obj = feature.get_Value(nameIndex); if (obj == null) continue; cityName = Convert.ToString(obj); obj = feature.get_Value(zipIndex); if (obj == null) continue; zip = long.Parse(Convert.ToString(obj)); if(zip <= 0) continue; //add the current location to the location table DataRow r = m_locations.Rows.Find(zip); if(null == r) { r = m_locations.NewRow(); r[1] = zip; r[2] = cityName; lock(m_locations) { m_locations.Rows.Add(r); } } feature = fCursor.NextFeature(); index++; } //release the feature cursor Marshal.ReleaseComObject(fCursor); } catch(Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } }
//线转面:测试不成功 private void feture2line(string CN_code, Geoprocessor gp, string outPath, string path, string name) { IWorkspaceFactory pwokspace = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = pwokspace.OpenFromFile(path, 0); IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)workspace; IFeatureClass featureClass = pFeatureWorkspace.OpenFeatureClass(name); //Msg("正在处理···" + CN_code + "···面转线"); ESRI.ArcGIS.DataManagementTools.FeatureToLine fe2li = new FeatureToLine(); fe2li.in_features = featureClass; fe2li.out_feature_class = outPath; gp.OverwriteOutput = true; gp.Execute(fe2li, null); MessageBox.Show(CN_code + "···面转线处理完成!"); }
private IFeatureClass loadFeatureClasFromFolder(string dir, string name) { IFeatureClass feacls = null; IWorkspace workspace; IName nameobj; IEnumDatasetName enumdsetName; IWorkspaceFactory wsFactory; wsFactory = new ShapefileWorkspaceFactoryClass(); workspace = wsFactory.OpenFromFile(dir, 0); enumdsetName = workspace.get_DatasetNames(esriDatasetType.esriDTFeatureClass); IDatasetName dname = enumdsetName.Next(); while (dname != null) { nameobj = dname as IName; string str = dname.Name; if (string.Equals(str, name)) { feacls = nameobj.Open() as IFeatureClass; return feacls; } dname = enumdsetName.Next(); } return feacls; }
private void AddASCFile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { this.openFileDialog1.Title = "加载路线数据"; this.openFileDialog1.Filter = "My file(*.txt)|*.txt|ShapeFile(*.shp)|*.shp"; if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { this.gridControl1.DataSource = null; if (this.PointsDt.Rows.Count != 0) { this.PointsDt.Clear(); } // int rCount = this.PointsDt.Rows.Count; if (this.openFileDialog1.FileName.ToLower().Contains(".txt")) { string[] CoorPoint = File.ReadAllLines(this.openFileDialog1.FileName, Encoding.ASCII); try { for (int j = 0; j < CoorPoint.Length; j++) { if (CoorPoint[j] != "" && CoorPoint[j] != null) { DataRow dr = PointsDt.NewRow(); string[] newStrArr = new string[2]; newStrArr = CoorPoint[j].Split(','); dr["X"] = newStrArr[0]; dr["Y"] = newStrArr[1]; PointsDt.Rows.Add(dr); } } this.gridControl1.DataSource = PointsDt; } catch (Exception ex) { MessageBox.Show("加载文件格式不正确!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); //throw; } } else if (this.openFileDialog1.FileName.ToLower().Contains(".shp")) { try { IWorkspaceFactory pShpWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace pWorkspace = pShpWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(this.openFileDialog1.FileName), 0); IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace; IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(this.openFileDialog1.FileName)); if (pFeatureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline) { MessageBox.Show("请导入线图层!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } IFeatureCursor fc = pFeatureClass.Search(null, false); IFeature pFeature = fc.NextFeature(); if (pFeature != null) { int sq = 0; ESRI.ArcGIS.Geometry.IGeometry geo = pFeature.Shape; ESRI.ArcGIS.Geometry.IPointCollection pPointCollection = geo as ESRI.ArcGIS.Geometry.IPointCollection; for (int i = 0; i < pPointCollection.PointCount; i++) { ESRI.ArcGIS.Geometry.IPoint pPoint = pPointCollection.get_Point(i); DataRow dr = PointsDt.NewRow(); dr["X"] = pPoint.X; dr["Y"] = pPoint.Y; PointsDt.Rows.Add(dr); } } } catch (Exception) { } if (PointsDt!=null) { this.gridControl1.DataSource = PointsDt; } } else { return; } } }
public IFeatureWorkspace GetFeatureWorkspaceFromDirectory(System.String string_ShapefileDirectory) { System.IO.DirectoryInfo directoryInfo_check = new System.IO.DirectoryInfo(string_ShapefileDirectory); if (directoryInfo_check.Exists) { IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(string_ShapefileDirectory, 0); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace; // Explict Cast return featureWorkspace; } else { // Not valid directory return null; } }
/// <summary> /// Export graphics to a shapefile /// </summary> /// <param name="fileNamePath">Path to shapefile</param> /// <param name="graphicsList">List of graphics for selected tab</param> /// <param name="ipSpatialRef">Spatial Reference being used</param> /// <returns>Created featureclass</returns> private IFeatureClass ExportToShapefile(string fileNamePath, List<Graphic> graphicsList, ISpatialReference ipSpatialRef) { int index = fileNamePath.LastIndexOf('\\'); string folder = fileNamePath.Substring(0, index); string nameOfShapeFile = fileNamePath.Substring(index + 1); string shapeFieldName = "Shape"; IFeatureClass featClass = null; using (ComReleaser oComReleaser = new ComReleaser()) { try { IWorkspaceFactory workspaceFactory = null; workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(folder, 0); IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; IFields fields = null; IFieldsEdit fieldsEdit = null; fields = new Fields(); fieldsEdit = (IFieldsEdit)fields; IField field = null; IFieldEdit fieldEdit = null; field = new FieldClass();///########### fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Shape"; fieldEdit.Type_2 = (esriFieldType.esriFieldTypeGeometry); IGeometryDef geomDef = null; IGeometryDefEdit geomDefEdit = null; geomDef = new GeometryDefClass();///######### geomDefEdit = (IGeometryDefEdit)geomDef; //This is for line shapefiles geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; geomDefEdit.SpatialReference_2 = ipSpatialRef; fieldEdit.GeometryDef_2 = geomDef; fieldsEdit.AddField(field); ////Add another miscellaneous text field //field = new FieldClass(); //fieldEdit = (IFieldEdit)field; //fieldEdit.Length_2 = 30; //fieldEdit.Name_2 = "TextField"; //fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; //fieldsEdit.AddField(field); featClass = featureWorkspace.CreateFeatureClass(nameOfShapeFile, fields, null, null, esriFeatureType.esriFTSimple, shapeFieldName, ""); foreach (Graphic graphic in graphicsList) { IFeature feature = featClass.CreateFeature(); feature.Shape = graphic.Geometry; feature.Store(); } IFeatureLayer featurelayer = null; featurelayer = new FeatureLayerClass(); featurelayer.FeatureClass = featClass; featurelayer.Name = featClass.AliasName; System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workspace); workspace = null; GC.Collect(); return featClass; } catch (Exception ex) { return featClass; } } }
private void btnOK_Click(object sender, EventArgs e) { if (this.cklstCurLayers.CheckedItems.Count == 0) { MessageBox.Show("请选择要导出的图层!"); return; } if (this.tbOutputFile.Text.Trim().Equals("")) { MessageBox.Show("请选择导出路径!"); return; } if (System.IO.Directory.Exists(this.tbOutputFile.Text) == false) { MessageBox.Show("导出路径不存在!"); return; } progressBar1.Maximum = cklstCurLayers.CheckedItems.Count; string outpath = this.tbOutputFile.Text + "\\"; List<IFeatureClass> list = new List<IFeatureClass>(); int succount = 0; try { for (int i = 0; i < this.cklstCurLayers.Items.Count; i++) { if (this.cklstCurLayers.GetItemChecked(i)) { list.Add(m_dicPathAliasName[i]); } } if (list.Count > 0) { IDataset pDataSet = list[0] as IDataset; IWorkspace pWorkspace = pDataSet.Workspace; IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pWS = (IFeatureWorkspace)pWSF.OpenFromFile(outpath, 0); for (int i = 0; i < list.Count; i++) { if (list[i].FeatureType == esriFeatureType.esriFTAnnotation) { MessageBox.Show("注记无法转换成shape格式!"); progressBar1.Value++; continue; } string fileName = (list[i] as IDataset).Name; string name = fileName.Substring(fileName.LastIndexOf('.') + 1); string fullFileName = outpath + name + ".shp"; fullFileName = fullFileName.Replace(@"//", @"/"); if (File.Exists(fullFileName)) { //如果已经存在就先删除 DirectoryInfo di = new DirectoryInfo(outpath); FileInfo[] fis = di.GetFiles(fileName + "*"); foreach (FileInfo fi in fis) { fi.Delete(); } } if (IFeatureDataConverter_ConvertFeatureClass(pWorkspace, (IWorkspace)pWS, fileName, name)) succount++; progressBar1.Value++; } } //GP.Execute(GPExportCAD, null); MessageBox.Show("成功转换" + succount.ToString() + "个图层!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 转格式 /// </summary> /// <param name="sourceWorkspacePath"></param> /// <param name="targetWorkspacePath"></param> /// <param name="sourceDataName"></param> /// <param name="targetDataName"></param> public static void ConvertFeatureClassToShapefile(string sourceWorkspacePath, string targetWorkspacePath, string sourceDataName, string targetDataName) { // Open the source and target workspaces. IWorkspaceFactory sourceWorkspaceFactory = new FileGDBWorkspaceFactoryClass(); IWorkspaceFactory targetWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace sourceWorkspace = sourceWorkspaceFactory.OpenFromFile(sourceWorkspacePath, 0); IWorkspace targetWorkspace = targetWorkspaceFactory.OpenFromFile(targetWorkspacePath, 0); // Cast the workspaces to the IDataset interface and get name objects. IDataset sourceWorkspaceDataset = (IDataset)sourceWorkspace; IDataset targetWorkspaceDataset = (IDataset)targetWorkspace; IName sourceWorkspaceDatasetName = sourceWorkspaceDataset.FullName; IName targetWorkspaceDatasetName = targetWorkspaceDataset.FullName; IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDatasetName; IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDatasetName; // Create a name object for the shapefile and cast it to the IDatasetName interface. IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass(); IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName; sourceDatasetName.Name = sourceDataName;//"streets"; sourceDatasetName.WorkspaceName = sourceWorkspaceName; // Create a name object for the FGDB feature class and cast it to the IDatasetName interface. IFeatureClassName targetFeatureClassName = new FeatureClassNameClass(); IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName; targetDatasetName.Name = targetDataName;// "AtlantaStreets"; targetDatasetName.WorkspaceName = targetWorkspaceName; // Open source feature class to get field definitions. IName sourceName = (IName)sourceFeatureClassName; IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open(); // Create the objects and references necessary for field validation. IFieldChecker fieldChecker = new FieldCheckerClass(); IFields sourceFields = sourceFeatureClass.Fields; IFields targetFields = null; IEnumFieldError enumFieldError = null; // Set the required properties for the IFieldChecker interface. fieldChecker.InputWorkspace = sourceWorkspace; fieldChecker.ValidateWorkspace = targetWorkspace; // Validate the fields and check for errors. fieldChecker.Validate(sourceFields, out enumFieldError, out targetFields); if (enumFieldError != null) { // Handle the errors in a way appropriate to your application. Console.WriteLine("Errors were encountered during field validation."); } // Find the shape field. String shapeFieldName = sourceFeatureClass.ShapeFieldName; int shapeFieldIndex = sourceFeatureClass.FindField(shapeFieldName); IField shapeField = sourceFields.get_Field(shapeFieldIndex); // Get the geometry definition from the shape field and clone it. IGeometryDef geometryDef = shapeField.GeometryDef; IClone geometryDefClone = (IClone)geometryDef; IClone targetGeometryDefClone = geometryDefClone.Clone(); IGeometryDef targetGeometryDef = (IGeometryDef)targetGeometryDefClone; // Create a query filter to remove ramps, interstates and highways. IQueryFilter queryFilter = new QueryFilterClass(); //queryFilter.WhereClause = "NAME <> 'Ramp' AND PRE_TYPE NOT IN ('I', 'Hwy')"; queryFilter.WhereClause = "1=1"; // Create the converter and run the conversion. IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass(); IEnumInvalidObject enumInvalidObject = featureDataConverter.ConvertFeatureClass(sourceFeatureClassName, queryFilter, null, targetFeatureClassName, targetGeometryDef, targetFields, "", 1000, 0); // Check for errors. IInvalidObjectInfo invalidObjectInfo = null; enumInvalidObject.Reset(); while ((invalidObjectInfo = enumInvalidObject.Next()) != null) { // Handle the errors in a way appropriate to the application. Console.WriteLine("Errors occurred for the following feature: {0}", invalidObjectInfo.InvalidObjectID); } }