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> /// <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); }
/// <summary> /// Occurs when this command is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { //Instantiate the hook helper if (m_hookHelper == null) { m_hookHelper = new HookHelperClass(); } //set the hook m_hookHelper.Hook = hook; //connect to the ZipCodes featureclass //get the ArcGIS path from the registry RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\ESRI\ArcObjectsSdk10.4"); string path = Convert.ToString(key.GetValue("InstallDir")); path = System.IO.Path.Combine(path, @"Samples\Data\USZipCodeData\"); IWorkspaceFactory wf = new ShapefileWorkspaceFactoryClass() as IWorkspaceFactory; IWorkspace ws = wf.OpenFromFile(path, 0); IFeatureWorkspace fw = ws as IFeatureWorkspace; m_featureClass = fw.OpenFeatureClass("US_ZipCodes"); m_spatialRefWGS84 = CreateGeoCoordSys(); }
/// <summary> /// Occurs when this command is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { //Instantiate the hook helper if (null == m_globeHookHelper) { m_globeHookHelper = new GlobeHookHelperClass(); } //set the hook m_globeHookHelper.Hook = hook; //get the relevant members IGlobe globe = m_globeHookHelper.Globe; m_scene = globe as IScene; m_globeDsp = m_globeHookHelper.GlobeDisplay; m_globeViewUtil = m_globeHookHelper.Camera as IGlobeViewUtil; //connect to the ZipCodes featureclass //get the ArcGIS path from the registry String versionNumber = RuntimeManager.ActiveRuntime.Version; RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\ESRI\ArcObjectsSdk" + versionNumber); string path = Convert.ToString(key.GetValue("InstallDir")); path = System.IO.Path.Combine(path, @"Samples\data\USZipCodeData"); IWorkspaceFactory wf = new ShapefileWorkspaceFactoryClass() as IWorkspaceFactory; IWorkspace ws = wf.OpenFromFile(path, 0); IFeatureWorkspace fw = ws as IFeatureWorkspace; m_featureClass = fw.OpenFeatureClass("US_ZipCodes"); }
/// <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); }
// // CONSTRUCTOR // public ShapeValidator() : base() { string tempPath = Path.GetTempPath(); string connection = string.Format("DATABASE={0}", tempPath); IWorkspaceFactory2 workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromString(connection, 0); this.SetWorkspace(workspace); }
public IFeatureClass CreateFeatureClass(string geometryType) { IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetTempPath(), 0); IFeatureClass featureClass; IFields fields; UID CLSID = new UIDClass(); CLSID.Value = "esriGeoDatabase.Feature"; IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass(); // create the fields using the required fields method fields = objectClassDescription.RequiredFields; string strShapeField = ""; // locate the shape field for (int j = 0; j < fields.FieldCount; j++) { if (fields.get_Field(j).Type == ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeGeometry) { strShapeField = fields.get_Field(j).Name; } } featureClass = featureWorkspace.CreateFeatureClass(tempFeatureLayerName, fields, CLSID, null, esriFeatureType.esriFTSimple, strShapeField, null); return(featureClass); }
static public IFeatureLayer OpenShapeData(IMap mapControl, OpenFileDialog OpenFdlg) { OpenFdlg.Title = "choose shape file"; OpenFdlg.Filter = "Shape file(*.shp)|*.shp"; OpenFdlg.ShowDialog(); string strFileName = OpenFdlg.FileName; if (strFileName == string.Empty) { return(null); } string pathName = System.IO.Path.GetDirectoryName(strFileName); string fileName = System.IO.Path.GetFileNameWithoutExtension(strFileName); IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(pathName, 0); IFeatureWorkspace pFeatureWorkspace; pFeatureWorkspace = pWorkspace as IFeatureWorkspace; IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(fileName); IDataset pDataset = pFeatureClass as IDataset; IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pFeatureClass; pFeatureLayer.Name = pDataset.Name; //ILayer pLayer = pFeatureLayer as ILayer; //mapControl.AddLayer(pLayer); InputFileOfName = strFileName; return(pFeatureLayer); }
//打开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; }
/// <summary> /// Exports to SHP. /// </summary> /// <param name="inputFeatureClass">The input feature class.</param> /// <param name="dataSourceType">Type of the data source.</param> /// <param name="saveShpFilePath">The save SHP file path.</param> public void ExportToShp(IFeatureClass inputFeatureClass, string dataSourceType, string saveShpFilePath) { IDataset dataset = inputFeatureClass as IDataset; string directoryName = Path.GetDirectoryName(saveShpFilePath); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(saveShpFilePath); IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(directoryName, 0); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } if (File.Exists(saveShpFilePath)) { IFeatureClass featureClass = (workspace as IFeatureWorkspace).OpenFeatureClass(fileNameWithoutExtension); IDataset dataset2 = featureClass as IDataset; if (!dataset2.CanDelete()) { XtraMessageBox.Show(AppMessage.MSG0112, AppMessage.MSG0000, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Asterisk); return; } string a = Path.Combine(dataset.Workspace.PathName, dataset.Name + ".shp"); if (a == saveShpFilePath && dataSourceType == "Shapefile Feature Class") { XtraMessageBox.Show(AppMessage.MSG0112, AppMessage.MSG0000, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Asterisk); return; } dataset2.Delete(); } this.SaveAsShpfile(inputFeatureClass, dataset, fileNameWithoutExtension, workspace); }
/// <summary> /// Occurs when this command is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { //Instantiate the hook helper if (null == m_globeHookHelper) { m_globeHookHelper = new GlobeHookHelperClass(); } //set the hook m_globeHookHelper.Hook = hook; //get the relevant members IGlobe globe = m_globeHookHelper.Globe; m_scene = globe as IScene; m_globeDsp = m_globeHookHelper.GlobeDisplay; m_globeViewUtil = m_globeHookHelper.Camera as IGlobeViewUtil; //connect to the ZipCodes featureclass string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); path = System.IO.Path.Combine(path, @"ArcGIS\data\USZipCodeData"); if (!Directory.Exists(path)) { throw new Exception(string.Format("Fix code to point to your sample data: {0} was not found", path)); } IWorkspaceFactory wf = new ShapefileWorkspaceFactoryClass() as IWorkspaceFactory; IWorkspace ws = wf.OpenFromFile(path, 0); IFeatureWorkspace fw = ws as IFeatureWorkspace; m_featureClass = fw.OpenFeatureClass("US_ZipCodes"); }
/// <summary> /// 创建FileGDB和PGDB Workspace /// @remark /// 1.Shp创建Workspace没有意义 /// 2.不支持SDE创建 /// </summary> /// <param name="wsType"></param> /// <param name="strPath"></param> /// <param name="strName"></param> /// <returns></returns> public static IWorkspace CreateWorkspace(enumWorkspaceType wsType, string strPath, string strName) { try { IWorkspaceFactory wsf = null; switch (wsType) { case enumWorkspaceType.SDE: throw new Exception("CreateWorkspace方法被设计为不支持SDE方式创建"); case enumWorkspaceType.FileGDB: wsf = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass(); break; case enumWorkspaceType.PGDB: wsf = new AccessWorkspaceFactoryClass(); break; case enumWorkspaceType.File: wsf = new ShapefileWorkspaceFactoryClass(); break; } IWorkspaceName wsName = wsf.Create(strPath, strName, null, 0); return((wsName as IName).Open() as IWorkspace); } catch { return(null); } }
//获取要素面积,单位为平方米 private double GetShpArea(string filePath) { string folder = Path.GetDirectoryName(filePath); string fileName = Path.GetFileName(filePath); double dArea = 0; IWorkspaceFactory pwsf = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWorkspace = pwsf.OpenFromFile(folder, 0) as IFeatureWorkspace; if (pFeatureWorkspace != null) { IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(fileName); IFeatureCursor pFeatureCursor = pFeatureClass.Search(null, false); IFeature pFeature = pFeatureCursor.NextFeature(); while (pFeature != null) { if (pFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon) { IArea pArea = pFeature.Shape as IArea; dArea = dArea + pArea.Area; } pFeature = pFeatureCursor.NextFeature(); } Marshal.ReleaseComObject(pFeatureCursor); } Marshal.ReleaseComObject(pwsf); return(dArea); }
/// <summary> /// 虚态方法没有实现 /// </summary> /// <returns></returns> public virtual 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, this.GeometryType); if (fc != null) { ESRI.ArcGIS.ADF.ComReleaser.ReleaseCOMObject(fc); System.Runtime.InteropServices.Marshal.ReleaseComObject(fc); fc = null; rbc = true; } ESRI.ArcGIS.ADF.ComReleaser.ReleaseCOMObject(objws); System.Runtime.InteropServices.Marshal.ReleaseComObject(objws); feaureWS = null; objws = null; objwsf = null; } catch (Exception ee) { Log.WriteLine(ee); rbc = false; } return(rbc); }
public IMap GetPastureByFilter(string strFilter) { string strSearchePattern = @"*" + strFilter + ".shp"; IMap pastureMap = new Map(); pastureMap.Name = strFilter; IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); foreach (GrassFamily family in m_grassFamilys) { foreach (Pasture pasture in family.pastures) { IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(pasture.strDataDir, 0); DirectoryInfo pastureDir = new DirectoryInfo(pasture.strDataDir); FileInfo[] files = pastureDir.GetFiles(strSearchePattern); foreach (FileInfo file in files) { IFeatureLayer featureLayer = new FeatureLayerClass(); featureLayer.Name = pasture.strPasture+"_"+file.Name; featureLayer.Visible = true; featureLayer.FeatureClass = workspace.OpenFeatureClass(file.Name); pastureMap.AddLayer(featureLayer); } } } //m_mapcontrol.Map = pastureMap; return pastureMap; }
/// <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); }
private void button1_Click(object sender, EventArgs e) { IGeoDataset inGeoDataSet; IGeoDataset outGeoDataSet; IConversionOp conversionOp = new RasterConversionOpClass(); // 构造inGeoDataSet ILayer layer = GetLayerByName(comboBox1.SelectedItem.ToString()); IRasterLayer rasterLayer = layer as IRasterLayer; IRaster raster = rasterLayer.Raster; inGeoDataSet = raster as IGeoDataset; IWorkspaceFactory2 pWorkspaceFactoryShp = new ShapefileWorkspaceFactoryClass(); IWorkspace pWorkspace = pWorkspaceFactoryShp.OpenFromFile(textBox1.Text, 0); ISpatialReference pSpatialReference = inGeoDataSet.SpatialReference; outGeoDataSet = conversionOp.RasterDataToPolygonFeatureData( inGeoDataSet, pWorkspace, textBox2.Text, true ); IDataset pDataset1 = outGeoDataSet as IDataset; IFeatureClass pFeatureClass = pDataset1 as IFeatureClass; IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pFeatureClass; pFeatureLayer.Name = textBox2.Text; mainForm.axMapControl1.AddLayer(pFeatureLayer); mainForm.axMapControl1.Refresh(); }
/// <summary> /// 打开shp为IFeatureClass /// </summary> /// <param name="inFile">shp文件名.</param> /// <returns>IFeatureClass.</returns> public static IFeatureClass OpenFeatureClass(string inFile) { IFeatureClass pFeatureClass = null; try { //获取当前路径和文件名 if (inFile != "") { IWorkspaceFactory pWorkspaceFactory; IFeatureWorkspace pFeatureWorkspace; 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(); pFeatureClass = pFeatureWorkspace.OpenFeatureClass(fileName); } return(pFeatureClass); } catch (Exception ex) { MessageBox.Show("打开矢量文件失败!/r" + ex.Message); return(null); } }
/// <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 InitMapCtr() { IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(@"D:\RasterMaSysTemp\hhData", 0); IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace; if (pFeatureWorkspace != null) { IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass("洪湖水域.shp"); IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.Name = "洪湖水域"; pFeatureLayer.FeatureClass = pFeatureClass; //设置为湖泊符号渲染 IGeoFeatureLayer pGeoFeatureLayer = (IGeoFeatureLayer)pFeatureLayer; IFillSymbol pFillSymbol = new SimpleFillSymbolClass(); pFillSymbol.Color = DataShowControl.GetColor(151, 219, 242); ILineSymbol pLineSymbol = new SimpleLineSymbolClass(); pLineSymbol.Color = DataShowControl.GetColor(64, 101, 235); pLineSymbol.Width = 0.4; pFillSymbol.Outline = pLineSymbol; ISimpleRenderer pSimpleRenderer = new SimpleRendererClass(); pSimpleRenderer.Symbol = (ISymbol)pFillSymbol; pGeoFeatureLayer.Renderer = pSimpleRenderer as IFeatureRenderer; //添加图层 axMapControl1.Map.AddLayer(pGeoFeatureLayer); axMapControl1.ActiveView.Extent = axMapControl1.ActiveView.FullExtent; } }
private void ExportFeature(IFeatureClass pInFeatureClass, string pPath) { //创建一个输出shp文件的工作空间 IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); string parentPath = pPath.Substring(0, pPath.LastIndexOf("\\")); string fileName = pPath.Substring(pPath.LastIndexOf("\\") + 1, pPath.Length - pPath.LastIndexOf("\\") - 1); IWorkspaceName pWorkspaceName = pWorkspaceFactory.Create(parentPath, fileName, null, 0); //创建一个要素类 IName name = (IName)pWorkspaceName; IWorkspace pOutWorkspace = (IWorkspace)name.Open(); IDataset pInDataset = pInFeatureClass as IDataset; IFeatureClassName pInFCName = pInDataset.FullName as IFeatureClassName; IWorkspace pInWorkspace = pInDataset.Workspace; IDataset pOutDataset = pOutWorkspace as IDataset; IWorkspaceName pOutWorkspaceName = pOutDataset.FullName as IWorkspaceName; IFeatureClassName pOutFCName = new FeatureClassNameClass(); IDatasetName pDatasetName = pOutFCName as IDatasetName; pDatasetName.WorkspaceName = pOutWorkspaceName; pDatasetName.Name = pInFeatureClass.AliasName; IFieldChecker pFieldChecker = new FieldCheckerClass(); pFieldChecker.InputWorkspace = pInWorkspace; pFieldChecker.ValidateWorkspace = pOutWorkspace; IFields pFields = pInFeatureClass.Fields; IFields pOutFields; IEnumFieldError pEnumFieldError; pFieldChecker.Validate(pFields, out pEnumFieldError, out pOutFields); IFeatureDataConverter pFeatureDataConverter = new FeatureDataConverterClass(); pFeatureDataConverter.ConvertFeatureClass(pInFCName, null, null, pOutFCName, null, pOutFields, "", 100, 0); }
public override void Execute(object parameter) { IWorkspaceFactory pWorkspaceFactory; IFeatureWorkspace pFeatureWorkspace; IFeatureLayer pFeatureLayer; // 获取当前路径和文件名 OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = " Shape(*.shp)|*.shp|All Files(*.*)|*.* "; dlg.Title = " Open Shapefile data "; dlg.ShowDialog(); string strFullPath = dlg.FileName; if (strFullPath == "") { return; } int Index = strFullPath.LastIndexOf(" // "); string filePath = strFullPath.Substring(0, Index); string fileName = strFullPath.Substring(Index + 1); // 打开工作空间并添加shp文件 pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(filePath, 0); pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pFeatureWorkspace.OpenFeatureClass(fileName); pFeatureLayer.Name = pFeatureLayer.FeatureClass.AliasName; MapControl.Map.AddLayer(pFeatureLayer); MapControl.ActiveView.Refresh(); }
/// <summary> /// 导入要素 /// </summary> /// <param name="featureClass"></param> /// <param name="btnImportFeature"></param> internal static void ImportFeature(ref IFeatureClass featureClass, ButtonEdit btnImportFeature) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = "添加Shape数据"; openFileDialog.Multiselect = false; openFileDialog.Filter = "Shape|*.shp"; openFileDialog.RestoreDirectory = true; openFileDialog.CheckFileExists = true; openFileDialog.Multiselect = false; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (openFileDialog.FileName != null) { IWorkspaceFactory shapeWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace shapeFeatureWorkspace = (IFeatureWorkspace)shapeWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(openFileDialog.FileName), 0); featureClass = shapeFeatureWorkspace.OpenFeatureClass(System.IO.Path.GetFileName(openFileDialog.FileName)); string aliasName = featureClass.AliasName; btnImportFeature.Invoke(new Action(() => { btnImportFeature.Text = aliasName; })); } else { featureClass = null; } } else { featureClass = null; } }
private void Btn_ExportSelection_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog() { Filter = "Shapefile|*.shp", }; if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { IWorkspaceFactory factory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace tempWorkspace = factory.OpenFromFile(sfd.FileName.Substring(0, sfd.FileName.LastIndexOf('\\')), 0) as IFeatureWorkspace; IFeatureClass curFeatureClass = (m_selectedLayer as IFeatureLayer).FeatureClass; IFeatureClass newFeatureClass = tempWorkspace.CreateFeatureClass("result", curFeatureClass.Fields, null, null, esriFeatureType.esriFTSimple, curFeatureClass.ShapeFieldName, ""); ICursor cursor; (m_selectedLayer as IFeatureSelection).SelectionSet.Search(null, true, out cursor); IFeatureCursor featureCursor = cursor as IFeatureCursor; IFeature curFeature = featureCursor.NextFeature(); while (curFeature != null) { IFeature newFeature = newFeatureClass.CreateFeature(); for (int i = 0; i < newFeatureClass.Fields.FieldCount; i++) { IField curField = newFeatureClass.Fields.get_Field(i); if (curField.Type != esriFieldType.esriFieldTypeOID) { newFeature.set_Value(i, curFeature.get_Value(i)); } } newFeature.Store(); curFeature = featureCursor.NextFeature(); } } }
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> /// 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); } }
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> /// 创建FileGDB和PGDB Workspace /// @remark /// 1.Shp创建Workspace没有意义 /// 2.不支持SDE创建 /// </summary> /// <param name="wsType"></param> /// <param name="strPath"></param> /// <param name="strName"></param> /// <returns></returns> public static IWorkspace CreateWorkspace(enumWorkspaceType wsType, string strPath, string strName) { try { IWorkspaceFactory wsf = null; switch (wsType) { case enumWorkspaceType.SDE: throw new Exception("CreateWorkspace方法被设计为不支持SDE方式创建"); case enumWorkspaceType.FileGDB: wsf = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass(); break; case enumWorkspaceType.PGDB: wsf = new AccessWorkspaceFactoryClass(); break; case enumWorkspaceType.File: wsf = new ShapefileWorkspaceFactoryClass(); break; } IWorkspaceName wsName = wsf.Create(strPath, strName, null, 0); return (wsName as IName).Open() as IWorkspace; } catch { return null; } }
//读取原始数据并添加到grouplayer列表中 public void LoadOriginData(string path, int groupNumber) { IWorkspaceFactory shpFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace shpFeaWksp = shpFactory.OpenFromFile(path, 0) as IFeatureWorkspace; IFeatureClass fcPoint = shpFeaWksp.OpenFeatureClass(pointFile); IFeatureClass fcLine = shpFeaWksp.OpenFeatureClass(lineFile); IFeatureClass fcPlygon = shpFeaWksp.OpenFeatureClass(polygonFile); IFeatureLayer lyPoint = new FeatureLayerClass(); lyPoint.FeatureClass = fcPoint; IFeatureLayer lyLine = new FeatureLayerClass(); lyLine.FeatureClass = fcLine; IFeatureLayer lyPlygon = new FeatureLayerClass(); lyPlygon.FeatureClass = fcPlygon; IGroupLayer grpLayer = new GroupLayerClass(); grpLayer.Name = "grp" + groupNumber.ToString() + "ext0"; grpLayer.Add(lyPoint); grpLayer.Add(lyLine); grpLayer.Add(lyPlygon); avlbLayers.Add(grpLayer); }
/// <summary> /// 执行矢量转栅格 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FtoR_backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; //设置CancellationPending可以退出任务线程 if (worker.CancellationPending == true) { e.Cancel = true; } else { try { FileInfo inputinfo = new FileInfo(featuretoraster_inputcombox.Text); FileInfo outputinfo = new FileInfo(featuretoraster_output.Text); IWorkspaceFactory outputworkspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace outputworkspaceop = outputworkspaceFactory.OpenFromFile(outputinfo.DirectoryName, 0);//创建输出工作空间 IWorkspaceFactory workspacefactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace featureworkspace = workspacefactory.OpenFromFile(inputinfo.DirectoryName, 0) as IFeatureWorkspace; IFeatureClass featureclass = featureworkspace.OpenFeatureClass(inputinfo.Name); IFeatureClassDescriptor featureClassDescriptor = new FeatureClassDescriptorClass(); featureClassDescriptor.Create(featureclass, null, featuretoraster_fieldcombox.Text); IGeoDataset geodatasetop = featureClassDescriptor as IGeoDataset; IConversionOp conversionOp = new RasterConversionOpClass(); //转换设置 IRasterAnalysisEnvironment rasterAnalysisEnvironment = conversionOp as IRasterAnalysisEnvironment; //栅格的大小 double dCellSize = Convert.ToDouble(featuretoraster_cellsize.Text); object oCellSize = dCellSize as object; //设置栅格大小 rasterAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref oCellSize); string format = ""; if (outputinfo.Extension == ".tif") { format = "TIFF"; } else if (outputinfo.Extension == ".img") { format = "IMAGINE Image"; } else { format = "GRID"; } //启动预处理计时 watch = new Stopwatch(); watch.Start(); //执行转换 conversionOp.ToRasterDataset(geodatasetop, format, outputworkspaceop, outputinfo.Name); } catch (Exception erro) { MessageBox.Show(erro.Message, "错误"); } } }
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> /// Opens the DBF table. /// </summary> /// <param name="dbfFileName">Name of the DBF file.</param> /// <returns></returns> public static ITable OpenDbfTable(string dbfFileName) { // Validate arguments if (string.IsNullOrEmpty(dbfFileName)) { throw new ArgumentNullException("dbfFileName", "DBF filename has not been set."); } if (!System.IO.Path.GetExtension(dbfFileName.ToLower()).Equals(".dbf")) { throw new ArgumentException("Input file must be DBF file format.", "dbfFileName"); } if (!File.Exists(dbfFileName)) { throw new FileNotFoundException(string.Format("{0} does not exist.", dbfFileName)); } // Get table name and directory string sourceTableName = System.IO.Path.GetFileNameWithoutExtension(dbfFileName); string sourceDirectory = System.IO.Path.GetDirectoryName(dbfFileName); // Open the shapefile (i.e. folder) workspace IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(sourceDirectory, 0); // ShapefileWorkspace does not implement IWorkspace2. So manually check if table exists. if (!TableExists(workspace, sourceTableName)) { throw new ArgumentException(string.Format("{0} is an invalid table.", sourceTableName)); } // Open and return the table IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; return(featureWorkspace.OpenTable(sourceTableName)); }
//添加图层 private void button1_Click(object sender, EventArgs e) { System.Windows.Forms.OpenFileDialog openFileDialog; openFileDialog = new OpenFileDialog(); openFileDialog.Title = "打开shp文件"; openFileDialog.Filter = "shp layer(*.shp)|*.shp"; if (openFileDialog.ShowDialog() == DialogResult.OK) { string file = openFileDialog.FileName; string filePath, fileName; int index = 0; index = file.LastIndexOf("\\"); filePath = file.Substring(0, index); fileName = file.Substring(index + 1, file.Length - index - 1); IWorkspaceFactory workspaceFactory; IFeatureWorkspace featureWorkspace; IFeatureLayer featureLayer; workspaceFactory = new ShapefileWorkspaceFactoryClass(); featureWorkspace = workspaceFactory.OpenFromFile(filePath, 0) as IFeatureWorkspace; featureLayer = new FeatureLayerClass(); featureLayer.FeatureClass = featureWorkspace.OpenFeatureClass(fileName); featureLayer.Name = featureLayer.FeatureClass.AliasName; this.axMapControl1.AddLayer(featureLayer as ILayer); CreatePolyline(); this.axMapControl1.Refresh(); } }
public void ExportFeature(IFeatureClass pInFeatureClass, string pPath) { // create a new Access workspace factory IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); string parentPath = pPath.Substring(0, pPath.LastIndexOf('\\')); string fileName = pPath.Substring(pPath.LastIndexOf('\\') + 1, pPath.Length - pPath.LastIndexOf('\\') - 1); IWorkspaceName pWorkspaceName = pWorkspaceFactory.Create(parentPath, fileName, null, 0); // Cast for IName IName name = (IName)pWorkspaceName; //Open a reference to the access workspace through the name object IWorkspace pOutWorkspace = (IWorkspace)name.Open(); IDataset pInDataset = pInFeatureClass as IDataset; IFeatureClassName pInFCName = pInDataset.FullName as IFeatureClassName; IWorkspace pInWorkspace = pInDataset.Workspace; IDataset pOutDataset = pOutWorkspace as IDataset; IWorkspaceName pOutWorkspaceName = pOutDataset.FullName as IWorkspaceName; IFeatureClassName pOutFCName = new FeatureClassNameClass(); IDatasetName pDatasetName = pOutFCName as IDatasetName; pDatasetName.WorkspaceName = pOutWorkspaceName; pDatasetName.Name = pInFeatureClass.AliasName; IFieldChecker pFieldChecker = new FieldCheckerClass(); pFieldChecker.InputWorkspace = pInWorkspace; pFieldChecker.ValidateWorkspace = pOutWorkspace; IFields pFields = pInFeatureClass.Fields; IFields pOutFields; IEnumFieldError pEnumFieldError; pFieldChecker.Validate(pFields, out pEnumFieldError, out pOutFields); IFeatureDataConverter pFeatureDataConverter = new FeatureDataConverterClass(); pFeatureDataConverter.ConvertFeatureClass(pInFCName, null, null, pOutFCName, null, pOutFields, "", 100, 0); }
/// <summary> /// 新建线图层 /// </summary> public void CreatePolylineLayer() { 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.esriGeometryPolyline; 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(); } }
/// <summary> /// Occurs when this command is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { //Instantiate the hook helper if (m_hookHelper == null) { m_hookHelper = new HookHelperClass(); } //set the hook m_hookHelper.Hook = hook; //connect to the ZipCodes featureclass string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); path = System.IO.Path.Combine(path, @"ArcGIS\data\USZipCodeData\"); if (!Directory.Exists(path)) { throw new Exception(string.Format("Fix code to point to your sample data: {0} was not found", path)); } IWorkspaceFactory wf = new ShapefileWorkspaceFactoryClass() as IWorkspaceFactory; IWorkspace ws = wf.OpenFromFile(path, 0); IFeatureWorkspace fw = ws as IFeatureWorkspace; m_featureClass = fw.OpenFeatureClass("US_ZipCodes"); m_spatialRefWGS84 = CreateGeoCoordSys(); }
/// <summary> /// 获取矢量工作空间 /// </summary> /// <param name="filePath">矢量文件路径</param> /// <returns></returns> public static IWorkspace GetShapefileWorkspace(string filePath) { string fileDir = Path.GetDirectoryName(filePath); IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); return(workspaceFactory.OpenFromFile(fileDir, 0)); }
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> /// /// </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 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> /// 打开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 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); }
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("SnapCommands_CS.SnapSettingsCommand", 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.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 = (CommandPool)axEditorToolbar.CommandPool; m_toolbarMenu.CommandPool = (CommandPool)axToolbarControl1.CommandPool; //add some sample line data to the map IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); 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); }
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(); } }
/// <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); } }
/// <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(); }
// // // 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); } }
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; } }
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); } }
/// <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; } } }
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 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; }
/// <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; } }
/// <summary> /// 要素类转Shape /// </summary> /// <param name="apFeatureClass"></param> private void ExportFeatureClassToConTempShp(IFeatureClass apFeatureClass) { if (Directory.Exists(System.Windows.Forms.Application.StartupPath + "\\Convert\\DWGConvert\\ConTempShp")) { Directory.Delete(System.Windows.Forms.Application.StartupPath + "\\Convert\\DWGConvert\\ConTempShp", true); } //设置导出要素类的参数 IFeatureClassName pOutFeatureClassName = new FeatureClassNameClass(); IDataset pOutDataset = (IDataset)apFeatureClass; pOutFeatureClassName = (IFeatureClassName)pOutDataset.FullName; //创建一个输出shp文件的工作空间 IWorkspaceFactory pShpWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspaceName pInWorkspaceName = new WorkspaceNameClass(); pInWorkspaceName = pShpWorkspaceFactory.Create(System.Windows.Forms.Application.StartupPath + "\\Convert\\DWGConvert", "ConTempShp", null, 0); //创建一个要素集合 IFeatureDatasetName pInFeatureDatasetName = null; //创建一个要素类 IFeatureClassName pInFeatureClassName = new FeatureClassNameClass(); IDatasetName pInDatasetClassName; pInDatasetClassName = (IDatasetName)pInFeatureClassName; pInDatasetClassName.Name = "ConTempShp";//作为输出参数 pInDatasetClassName.WorkspaceName = pInWorkspaceName; //通过FIELDCHECKER检查字段的合法性,为输出SHP获得字段集合 long iCounter; IFields pOutFields, pInFields; IFieldChecker pFieldChecker; IField pGeoField; IEnumFieldError pEnumFieldError = null; pInFields = apFeatureClass.Fields; pFieldChecker = new FieldChecker(); pFieldChecker.Validate(pInFields, out pEnumFieldError, out pOutFields); //通过循环查找几何字段 pGeoField = null; for (iCounter = 0; iCounter < pOutFields.FieldCount; iCounter++) { if (pOutFields.get_Field((int)iCounter).Type == esriFieldType.esriFieldTypeGeometry) { pGeoField = pOutFields.get_Field((int)iCounter); break; } } //得到几何字段的几何定义 IGeometryDef pOutGeometryDef; IGeometryDefEdit pOutGeometryDefEdit; pOutGeometryDef = pGeoField.GeometryDef; //设置几何字段的空间参考和网格 pOutGeometryDefEdit = (IGeometryDefEdit)pOutGeometryDef; pOutGeometryDefEdit.GridCount_2 = 1; pOutGeometryDefEdit.set_GridSize(0, 1500000); //try //{ IFeatureDataConverter pShpToClsConverter = new FeatureDataConverterClass(); pShpToClsConverter.ConvertFeatureClass(pOutFeatureClassName, null, pInFeatureDatasetName, pInFeatureClassName, pOutGeometryDef, pOutFields, "", 1000, 0); // MessageBox.Show("导出成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information); //} //catch (Exception ex) //{ //} /*****20130227杨漾(去掉trycatch,上层trycatch(MainForm)处理)*****/ }
public IWorkspace CreateWorkspaceGdbFile(string path, string name, string type) { try { IWorkspace wp; IWorkspaceName wpn; IName nwp; IWorkspaceFactory2 wspf; Directory.CreateDirectory(path); path = path + "\\"; switch (type) { case "mdb": wspf = new AccessWorkspaceFactoryClass(); name = name + ".mdb"; break; case "shp": wspf = new ShapefileWorkspaceFactoryClass(); break; default: wspf = new ShapefileWorkspaceFactoryClass(); break; } wpn = wspf.Create(path, name, null, 0); nwp = (IName)wpn; wp = (IWorkspace)nwp.Open(); return wp; } 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> /// 储存凸包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(); */ }
//����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; }