//裁剪图层要素 打开 按钮 private void button2_Click(object sender, EventArgs e) { // Use the OpenFileDialog Class to choose which shapefile to load. System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog(); //openFileDialog.InitialDirectory = "c:\\"; openFileDialog.Filter = "Shapefiles (*.shp)|*.shp"; openFileDialog.FilterIndex = 2; openFileDialog.RestoreDirectory = true; openFileDialog.Multiselect = false; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { // The user chose a particular shapefile. // The returned string will be the full path, filename and file-extension for the chosen shapefile. Example: "C:\test\cities.shp" string shapefileLocation = openFileDialog.FileName; txtClipsFile.Text = shapefileLocation; if (shapefileLocation != "") { // Ensure the user chooses a shapefile // Create a new ShapefileWorkspaceFactory CoClass to create a new workspace ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass(); // System.IO.Path.GetDirectoryName(shapefileLocation) returns the directory part of the string. Example: "C:\test\" ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(shapefileLocation), 0); // Explicit Cast // System.IO.Path.GetFileNameWithoutExtension(shapefileLocation) returns the base filename (without extension). Example: "cities" ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(shapefileLocation)); ESRI.ArcGIS.Carto.IFeatureLayer featureLayer = new ESRI.ArcGIS.Carto.FeatureLayerClass(); featureLayer.FeatureClass = featureClass; featureLayer.Name = featureClass.AliasName; featureLayer.Visible = true; //activeView.FocusMap.AddLayer(featureLayer); // Zoom the display to the full extent of all layers in the map //activeView.Extent = activeView.FullExtent; // activeView.PartialRefresh(ESRI.ArcGIS.Carto.esriViewDrawPhase.esriViewGeography, null, null); } else { // The user did not choose a shapefile. // Do whatever remedial actions as necessary System.Windows.Forms.MessageBox.Show("No shapefile chosen", "No Choice #1", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } } else { // The user did not choose a shapefile. They clicked Cancel or closed the dialog by the "X" button. // Do whatever remedial actions as necessary. System.Windows.Forms.MessageBox.Show("No shapefile chosen", "No Choice #2", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } }
/// <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 ESRI.ArcGIS.Geodatabase.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 ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass(); ESRI.ArcGIS.Geodatabase.IWorkspace workspace = workspaceFactory.OpenFromFile(string_ShapefileDirectory, 0); ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace; // Explict Cast ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(string_ShapefileName); return(featureClass); } else { //Not valid shapefile return(null); } } else { // Not valid directory return(null); } }
private IFeatureClass getShapeFile(string inDir, string infile) { System.IO.DirectoryInfo directoryInfo_check = new System.IO.DirectoryInfo(inDir); if (directoryInfo_check.Exists) { //We have a valid directory, proceed System.IO.FileInfo fileInfo_check = new System.IO.FileInfo(inDir + "\\" + infile + ".shp"); if (fileInfo_check.Exists) { //We have a valid shapefile, proceed ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass(); ESRI.ArcGIS.Geodatabase.IWorkspace workspace = workspaceFactory.OpenFromFile(inDir, 0); ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace; // Explict Cast ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(infile); return(featureClass); } else { //Not valid shapefile return(null); } } else { // Not valid directory return(null); } }
// Öppnar shapefil. public void AddShapefileUsingOpenFileDialog(ESRI.ArcGIS.Carto.IActiveView activeView) { //parameter check if (activeView == null) { return; } // Use the OpenFileDialog Class to choose which shapefile to load. System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog(); openFileDialog.InitialDirectory = @"H:\VT2019\GIS_App\Projekt\Program\Data\InData\Vektor"; openFileDialog.Filter = "Shapefiles (*.shp)|*.shp"; openFileDialog.FilterIndex = 2; openFileDialog.RestoreDirectory = true; openFileDialog.Multiselect = false; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { // The user chose a particular shapefile. // The returned string will be the full path, filename and file-extension for the chosen shapefile. Example: "C:\test\cities.shp" string shapefileLocation = openFileDialog.FileName; if (shapefileLocation != "") { // Ensure the user chooses a shapefile // Create a new ShapefileWorkspaceFactory CoClass to create a new workspace ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass(); // System.IO.Path.GetDirectoryName(shapefileLocation) returns the directory part of the string. Example: "C:\test\" ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(shapefileLocation), 0); // Explicit Cast // System.IO.Path.GetFileNameWithoutExtension(shapefileLocation) returns the base filename (without extension). Example: "cities" ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(shapefileLocation)); ESRI.ArcGIS.Carto.IFeatureLayer featureLayer = new ESRI.ArcGIS.Carto.FeatureLayerClass(); featureLayer.FeatureClass = featureClass; featureLayer.Name = featureClass.AliasName; featureLayer.Visible = true; activeView.FocusMap.AddLayer(featureLayer); // Zoom the display to the full extent of all layers in the map activeView.Extent = activeView.FullExtent; activeView.PartialRefresh(ESRI.ArcGIS.Carto.esriViewDrawPhase.esriViewGeography, null, null); } else { } } else { } }
public static IFeatureClass ReadFeatureClass(string path) { ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass(); // workspaceFactory.OpenFromFile,传入的参数是Shapefile文件所在的文件夹路径 string pathwithoutname = path.Substring(0, path.LastIndexOf("\\")); string namewithextention = path.Substring(path.LastIndexOf("\\") + 1); string name = namewithextention.Substring(0, namewithextention.LastIndexOf(".")); ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspaceFactory.OpenFromFile(pathwithoutname, 0); // OpenFeatureClass传入的参数是shape文件的文件名,不带后缀 ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(name); return(featureClass); }
public static ESRI.ArcGIS.Geodatabase.IFeatureClass getFeatureClass(string fPath) { { string featureClass = System.IO.Path.GetFileName(fPath); ESRI.ArcGIS.Geodatabase.IFeatureWorkspace fws = getWorkspace(fPath); try { return(fws.OpenFeatureClass(featureClass)); } catch (System.Runtime.InteropServices.COMException) { throw new System.IO.FileNotFoundException("Feature Class not found in workspace:\n" + fPath); } } }
public ESRI.ArcGIS.Geodatabase.IFeatureClass GetFeatureClassFromShapefileOnDisk(System.String string_ShapefileName, out ESRI.ArcGIS.Geodatabase.IWorkspace workspace) { //We have a valid directory, proceed System.IO.FileInfo fileInfo_check = new System.IO.FileInfo(string_ShapefileName); if (fileInfo_check.Exists) { //We have a valid shapefile, proceed ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactory(); workspace = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(string_ShapefileName), 0); ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace; // Explict Cast ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(System.IO.Path.GetFileName(string_ShapefileName)); return(featureClass); } else { workspace = null; //Not valid shapefile return(null); } }
private void OpenCADFile(string filePath, string outputFilePath) { try { Debug.WriteLine("Start Time: " + DateTime.Now.ToShortTimeString()); System.Windows.Forms.Cursor.Current = Cursors.WaitCursor; String nameOfPath = System.IO.Path.GetDirectoryName(filePath); String nameOfCADFile = System.IO.Path.GetFileName(filePath); #region Open CAD Workspace from File Path //Set the workspace. ESRI.ArcGIS.Geodatabase.IWorkspaceFactory pWorkspaceFact = new ESRI.ArcGIS.DataSourcesFile.CadWorkspaceFactory(); ESRI.ArcGIS.Geodatabase.IWorkspaceFactory defaultWorkspaceFact = new FileGDBWorkspaceFactory(); //Open the workspace. ESRI.ArcGIS.Geodatabase.IWorkspace pWorkspace = pWorkspaceFact.OpenFromFile(nameOfPath, 0); //Get the CADDrawingWorkspace. ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace pCadDwgWorkspace; pCadDwgWorkspace = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace)pWorkspace; //Open the CadDrawingDataset. ESRI.ArcGIS.DataSourcesFile.ICadDrawingDataset pCadDwgDataset; pCadDwgDataset = pCadDwgWorkspace.OpenCadDrawingDataset(nameOfCADFile); //Set the feature workspace. ESRI.ArcGIS.Geodatabase.IFeatureWorkspace pFeatureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)pWorkspace; //Open the Feature Class. #endregion #region Getting Polygon, polylines, and annotation from Cad file ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polygon")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Plyline = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polyline")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Anno = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Annotation")); #endregion UID CLSID_def = new UIDClass(); CLSID_def.Value = "esriGeoDatabase.Feature"; #region Creating Layers from Feature Classes //Polygons ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer.FeatureClass = pFeatClass; pFeatLayer.Name = "Polygons"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer; //Annotation ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Anno = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Anno.FeatureClass = pFeatClass_Anno; pFeatLayer_Anno.Name = "Annotation"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Anno = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Anno; //Polylines ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Plyline = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Plyline.FeatureClass = pFeatClass_Plyline; pFeatLayer_Plyline.Name = "Polylines"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Plyline = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Plyline; #endregion #region Creating In-Memory workspace IWorkspaceFactory WF = new InMemoryWorkspaceFactory(); ESRI.ArcGIS.esriSystem.IName name = WF.Create("", "MyWorkspace", null, 0) as ESRI.ArcGIS.esriSystem.IName; IWorkspace inMemWorkspace = (IWorkspace)name.Open(); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)inMemWorkspace; #endregion #region Creating new Fields IObjectClassDescription objectClassDescription = new FeatureClassDescription(); // create the fields using the required fields method IFields exportFields = new Fields(); IFieldsEdit fieldsEdit = (IFieldsEdit)exportFields; //OID IField field = new Field(); IField oidField = new Field(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); // Create a geometry definition (and spatial reference) for the feature class IGeometryDef geometryDef = new GeometryDef(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; IGeoDataset dataSet = (IGeoDataset)pFeatClass.FeatureDataset; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironment(); ISpatialReference spatialReference = dataSet.SpatialReference; ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Add a geometry field to the fields collection. This is where the geometry definition is applied. IField geometryField = new Field(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); #endregion #region Creating New Shapefile for Final output UID CLSID = new UIDClass(); CLSID.Value = "esriGeoDatabase.Feature"; //using the In-Memory Workspace created above IFeatureClass output = featureWorkspace.CreateFeatureClass("myPolygons", pFeatClass.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass polylines_cleaned = featureWorkspace.CreateFeatureClass("polylines_cleaned", pFeatClass_Plyline.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass annotation_cleaned = featureWorkspace.CreateFeatureClass("annotation_cleaned", pFeatClass_Anno.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); #endregion #region Appending features from CADWorkspaceFeatureClass to In-Memory FeatureClass Because Update cursor not in Cad workspace Geoprocessor GP = new Geoprocessor(); //Polylines ESRI.ArcGIS.DataManagementTools.Append append = new Append(); append.inputs = pFeatClass_Plyline; append.target = polylines_cleaned; GP.Execute(append, null); //System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Plyline); GC.Collect(); //Annotation append = new Append(); append.inputs = pFeatClass_Anno; append.target = annotation_cleaned; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Anno); GC.Collect(); //Polygons to output append = new Append(); append.inputs = pFeatClass; append.target = output; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass); GC.Collect(); #endregion #region Query Filter to Filter Layers string queryString = ""; //using the checked box list and comma seperated list to create where clause string //Adding Items from Check Box List foreach (var checkedItem in checkedListBox1.CheckedItems) { queryString = queryString + "Layer NOT LIKE '" + checkedItem.ToString() + "' AND "; } //Adding Items from Comma separated string if (textBox_commaSeparated.Text.Length > 0) { foreach (var item in textBox_commaSeparated.Text.Split(',')) { queryString = queryString + "Layer NOT LIKE '" + item.ToString() + "' AND "; } } //Removing Last 'AND' FROM queryString if (queryString.Length > 0) //if Atleast one item added { queryString = queryString.Remove(queryString.Length - 4); } IQueryFilter queryFilter = new QueryFilter(); queryFilter.SubFields = ""; if (queryString.Length > 0) { queryFilter.WhereClause = queryString; } else { queryFilter.WhereClause = "1=1"; } #endregion #region Removing Null Geometries string ignoreList = queryString.Replace("Layer NOT LIKE '", "").Replace("' AND ", ",").Replace("' ", ""); Debug.WriteLine("lines Count before:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From Polylines_cleaned IFeatureCursor updateCursor = polylines_cleaned.Update(new QueryFilter(), false); IFeature feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); //System.Runtime.InteropServices.Marshal.ReleaseComObject(feat); GC.Collect(); Debug.WriteLine("lines Count After:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From output Debug.WriteLine("polygons Count before:" + output.FeatureCount(new QueryFilter()).ToString()); updateCursor = output.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("polygons Count after:" + output.FeatureCount(new QueryFilter()).ToString()); //From Annotation Debug.WriteLine("Annotation Count before:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); updateCursor = annotation_cleaned.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("Annotation Count after:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); #endregion #region Convert lines feature class to feature Cursor IFeatureCursor linesFCursor = polylines_cleaned.Search(new QueryFilter(), false); #endregion #region Deleting all columns of polygons to match with output IFields _fieldsP = output.Fields; IFieldsEdit _fieldsEditP = (IFieldsEdit)_fieldsP; for (int i = 0; i < output.Fields.FieldCount; i++) { IField _field = output.Fields.get_Field(i); if (_field.Name != "Shape" && _field.Name != "FID") { output.DeleteField(_field); if (i < output.Fields.FieldCount) { i--; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsP); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEditP); GC.Collect(); #endregion #region Setting Envelop information IEnvelope envelop = new Envelope() as IEnvelope; IGeoDataset dataSetEnv = (IGeoDataset)pFeatClass_Plyline.FeatureDataset; envelop.SpatialReference = dataSet.SpatialReference; envelop.PutCoords(dataSet.Extent.XMin, dataSet.Extent.YMin, dataSet.Extent.XMax, dataSet.Extent.YMax); #endregion #region Construct Polygons from Lines Cursor (usting Feature Construct) IFeatureConstruction featureConstruct = new FeatureConstruction() as IFeatureConstruction; ISelectionSet selectionSet = null; //atureConstruct.ConstructPolygonsFromFeaturesFromCursor(null,output,envelop,false,false,linesFCursor,null,0.001,null); featureConstruct.AutoCompleteFromFeaturesFromCursor(output, envelop, linesFCursor, null, -1, null, out selectionSet); #endregion System.Runtime.InteropServices.Marshal.ReleaseComObject(featureConstruct); System.Runtime.InteropServices.Marshal.ReleaseComObject(linesFCursor); GC.Collect(); Debug.WriteLine("polygons Count after PolygonConstruct :" + output.FeatureCount(new QueryFilter()).ToString()); #region SPATIAL JOIN GP = new Geoprocessor(); ESRI.ArcGIS.AnalysisTools.SpatialJoin spatialJoin = new ESRI.ArcGIS.AnalysisTools.SpatialJoin(); spatialJoin.join_features = annotation_cleaned; spatialJoin.target_features = output; spatialJoin.join_operation = "JOIN_ONE_TO_MANY"; spatialJoin.join_type = "KEEP_ALL"; spatialJoin.match_option = "CONTAINS"; spatialJoin.out_feature_class = outputFilePath; GP.Execute(spatialJoin, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(annotation_cleaned); GC.Collect(); #endregion #region Remove All Fields of Annotation except Text ShapefileWorkspaceFactory wsf = new ShapefileWorkspaceFactory(); IFeatureWorkspace work = (IFeatureWorkspace)wsf.OpenFromFile(System.IO.Path.GetDirectoryName(outputFilePath), 0); IFeatureClass output_AfterJoin_FClasss = work.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(outputFilePath)); IFields _fields = output_AfterJoin_FClasss.Fields; IFieldsEdit _fieldsEdit = (IFieldsEdit)_fields; for (int i = 0; i < _fields.FieldCount; i++) { IField _field = output_AfterJoin_FClasss.Fields.get_Field(i); if (_field.Name != "Text_" && _field.Name != "Text" && _field.Name != "Shape" && _field.Name != "FID") { output_AfterJoin_FClasss.DeleteField(_field); i--; } else { if (field.Name == "Text_" || _field.Name == "Text") { IFieldEdit fieldEdit = (IFieldEdit)_field; fieldEdit.Name_2 = "PlotNumber"; fieldEdit.AliasName_2 = "PlotNumber"; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fields); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEdit); GC.Collect(); #endregion System.Windows.Forms.Cursor.Current = Cursors.Default; Debug.WriteLine("End Time: " + DateTime.Now.ToShortTimeString()); MessageBox.Show("Import Complete!"); } catch { MessageBox.Show("Error Importing. Something wrong with the CAD File"); } }
public static IFeatureClass createGoogleMapsEngineCatalogFeatureClass(ref log4net.ILog log, ref GoogleMapsEngineToolsExtensionForArcGIS ext) { try { // temporary directory to store workspace string workspacedirectory = ext.getLocalWorkspaceDirectory().FullName; // add the directory to the cleanup list // TODO: Replace with scratch ext.addTemporaryDirectory(new System.IO.DirectoryInfo(workspacedirectory)); // determine the workspace name for the geodatabase //string workspacefoldername = Properties.Settings.Default.extension_gdb_workspacename; // TODO: Use sctach workspace instead of creating a temporary one string workspacefoldername = "GME_Data_" + System.Guid.NewGuid().ToString().Replace("-", ""); // define a workspace to do work IWorkspace workspace = null; // attempt to open or create the workspace try { // check to see if the workspace already exists, if so, open it if (System.IO.Directory.Exists(workspacedirectory + "\\" + workspacefoldername)) { workspace = Extension.Data.GeodatabaseUtilities.openFileGeodatabaseWorkspace(ref log, workspacedirectory, workspacefoldername); ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace; ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(Properties.Resources.GeodatabaseUtilities_schema_FeatureClassName); ESRI.ArcGIS.Geodatabase.IDataset pdataset = (ESRI.ArcGIS.Geodatabase.IDataset)featureClass; if (pdataset.CanDelete()) { pdataset.Delete(); } pdataset = null; featureClass = null; featureWorkspace = null; // TODO: Open instead of delete/replace //if (arcgis.ext.gdb.GeodatabaseUtilities.deleteFileGeodatabaseWorkspace(workspacedirectory, workspacefoldername)) //workspace = arcgis.ext.gdb.GeodatabaseUtilities.createFileGeodatabaseWorkspace(workspacedirectory, workspacefoldername); } else { // workspace doesn't exist, create the workspace workspace = Extension.Data.GeodatabaseUtilities.createFileGeodatabaseWorkspace(ref log, workspacedirectory, workspacefoldername); } } catch (System.Exception ex) { // unable to create the fgdb or unable to delete the fc within the fgdb log.Error(ex); System.Windows.Forms.MessageBox.Show("Unable to create or delete an existing feature class."); } // verify the workspace is open if (workspace != null) { // create a new feature workspace to work spatially IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; // create a spatial reference for the Google Earth Builder data (always in 4326) SpatialReferenceEnvironment sRefEnvGEB = new SpatialReferenceEnvironment(); ISpatialReference sGEBRef = sRefEnvGEB.CreateGeographicCoordinateSystem(4326); // for this feature class, create and determine the field IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; fieldsEdit.FieldCount_2 = 10; //Create the Object ID field. IField fusrDefinedField = new Field(); IFieldEdit fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_OBJECTID_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_OBJECTID_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.set_Field(0, fusrDefinedField); //Create the CustomerId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_CustomerId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(1, fusrDefinedField); //Create the MapAssetId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(2, fusrDefinedField); //Create the AssetId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(3, fusrDefinedField); //Create the ParentAssetId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(4, fusrDefinedField); //Create the AssetType field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetType_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(5, fusrDefinedField); //Create the AssetName field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetName_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(6, fusrDefinedField); //Create the AssetDescription field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(7, fusrDefinedField); //Create the MapSharedWith field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_MapSharedWith_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_MapSharedWith_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(8, fusrDefinedField); // Create the Shape field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; // Set up the geometry definition for the Shape field. IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon; // By setting the grid size to 0, you're allowing ArcGIS to determine the appropriate grid sizes for the feature class. // If in a personal geodatabase, the grid size will be 1000. If in a file or ArcSDE geodatabase, the grid size // will be based on the initial loading or inserting of features. geometryDefEdit.GridCount_2 = 1; geometryDefEdit.set_GridSize(0, 0); geometryDefEdit.HasM_2 = false; geometryDefEdit.HasZ_2 = false; //Assign the spatial reference that was passed in, possibly from //IGeodatabase.SpatialReference for the containing feature dataset. geometryDefEdit.SpatialReference_2 = sGEBRef; // Set standard field properties. fusrDefinedFieldEdit.Name_2 = "SHAPE"; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; fusrDefinedFieldEdit.GeometryDef_2 = geometryDef; fusrDefinedFieldEdit.IsNullable_2 = true; fusrDefinedFieldEdit.Required_2 = true; fieldsEdit.set_Field(9, fusrDefinedField); // Create a feature class description object to use for specifying the CLSID and EXTCLSID. IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc; IFeatureClass fc = featureWorkspace.CreateFeatureClass( Properties.Resources.GeodatabaseUtilities_schema_FeatureClassName, // Feature Class Name fields, // Feature Class Fields (defined above) ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDesc.ShapeFieldName, // Shape Field Name "" // Keyword Configurations ); // return the feature class return(fc); } else { // end gracefully, maybe prompt the user that the toolbar wasn't able to create a workspcae throw new Exception("Unable to open local geodatabase."); } } catch (System.Exception ex) { // an error occured log.Error(ex); // throw an exception throw new Exception("An unknown exception occured while attempting to create a local feature class."); } }
public static IFeatureClass CreateFeatureClassInPGDB(IWorkspace2 workspace, IFeatureDataset featureDataset, string featureClassName, IFields fields, UID CLSID, UID CLSEXT, string strConfigKeyword, esriGeometryType esriGeometryType) { if (featureClassName == "") { return(null); // name was not passed in } ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass; ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace; // Explicit Cast if (workspace.get_NameExists(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTFeatureClass, featureClassName)) //feature class with that name already exists { featureClass = featureWorkspace.OpenFeatureClass(featureClassName); return(featureClass); } // assign the class id value if not assigned if (CLSID == null) { CLSID = new ESRI.ArcGIS.esriSystem.UIDClass(); CLSID.Value = "esriGeoDatabase.Feature"; } ESRI.ArcGIS.Geodatabase.IObjectClassDescription objectClassDescription = new ESRI.ArcGIS.Geodatabase.FeatureClassDescriptionClass(); // if a fields collection is not passed in then supply our own if (fields == null) { // create the fields using the required fields method fields = objectClassDescription.RequiredFields; ESRI.ArcGIS.Geodatabase.IFieldsEdit fieldsEdit = (ESRI.ArcGIS.Geodatabase.IFieldsEdit)fields; // Explicit Cast ESRI.ArcGIS.Geodatabase.IField field = new ESRI.ArcGIS.Geodatabase.FieldClass(); // create a user defined text field ESRI.ArcGIS.Geodatabase.IFieldEdit fieldEdit = (ESRI.ArcGIS.Geodatabase.IFieldEdit)field; // Explicit Cast // setup field properties fieldEdit.Name_2 = "SampleField"; fieldEdit.Type_2 = ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeString; fieldEdit.IsNullable_2 = true; fieldEdit.AliasName_2 = "Sample Field Column"; fieldEdit.DefaultValue_2 = "test"; fieldEdit.Editable_2 = true; fieldEdit.Length_2 = 100; // add field to field collection fieldsEdit.AddField(field); fields = (ESRI.ArcGIS.Geodatabase.IFields)fieldsEdit; // Explicit Cast } System.String strShapeField = ""; // locate the shape field for (int j = 0; j < fields.FieldCount; j++) { if (fields.get_Field(j).Type == esriFieldType.esriFieldTypeGeometry) { strShapeField = fields.get_Field(j).Name; ((IGeometryDefEdit)fields.get_Field(j).GeometryDef).GeometryType_2 = esriGeometryType; } } // Use IFieldChecker to create a validated fields collection. ESRI.ArcGIS.Geodatabase.IFieldChecker fieldChecker = new ESRI.ArcGIS.Geodatabase.FieldCheckerClass(); ESRI.ArcGIS.Geodatabase.IEnumFieldError enumFieldError = null; ESRI.ArcGIS.Geodatabase.IFields validatedFields = null; fieldChecker.ValidateWorkspace = (ESRI.ArcGIS.Geodatabase.IWorkspace)workspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); // The enumFieldError enumerator can be inspected at this point to determine // which fields were modified during validation. // finally create and return the feature class if (featureDataset == null)// if no feature dataset passed in, create at the workspace level { featureClass = featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, CLSID, CLSEXT, ESRI.ArcGIS.Geodatabase.esriFeatureType.esriFTSimple, strShapeField, strConfigKeyword); } else { featureClass = featureDataset.CreateFeatureClass(featureClassName, validatedFields, CLSID, CLSEXT, ESRI.ArcGIS.Geodatabase.esriFeatureType.esriFTSimple, strShapeField, strConfigKeyword); } return(featureClass); }