public static void DeleteFeatureClass(IDataset data) { if (data.CanDelete()) { data.Delete(); } }
//3/10/2009 删除工作空间内的所有要素类 public static void DeleteAllFeatCls(IWorkspace pworkspace) { IEnumDataset pEnumFeatDataset = default(IEnumDataset); IDataset pDataset = default(IDataset); IFeatureDataset pFeatDataset = default(IFeatureDataset); pEnumFeatDataset = pworkspace.get_Datasets(esriDatasetType.esriDTAny); pEnumFeatDataset.Reset(); pDataset = pEnumFeatDataset.Next(); while ((pDataset != null)) { if (pDataset.CanDelete()) { if (pDataset.Type == esriDatasetType.esriDTFeatureDataset) { pFeatDataset = (IFeatureDataset)pDataset; pFeatDataset.Delete(); } else { pDataset.Delete(); } //pDataset.Delete() pDataset = pEnumFeatDataset.Next(); } } }
/// <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); }
protected virtual void Dispose(bool disposing) { if (true == disposed) { return; } if (disposing) { /* * http://help.arcgis.com/en/sdk/10.0/arcobjects_net/componenthelp/index.html#/InMemoryWorkspaceFactoryClass_Class/001m0000002q000000/ * When an in-memory workspace is no longer needed, it is the developer's responsibility to call IDataset.Delete on the workspace to release its memory. * * I am not sure the memory held by idataset is managed or unmanaged, currently treat it as "unmanaged" */ if (null != workspace && workspace is IDataset) { IDataset dataset = workspace as IDataset; if (null != dataset && dataset.CanDelete()) { dataset.Delete(); } this.releaseCOMObj(this.workspace); this.releaseCOMObj(this.workspaceName); } } disposed = true; }
public static void JTDelete(this IDataset ds) { if (ds == null || !ds.CanDelete()) { return; } ds.Delete(); }
/// <summary> /// 删除数据集 /// </summary> /// <param name="pDataset"></param> public static void DeleteDataset(IDataset pDataset) { if (pDataset.CanDelete()) { pDataset.Delete(); } else { MessageBox.Show("无法删除该数据集!"); } }
public static void DeleteFeatureClass(IFeatureClass featureClass) { IDataset pDataset = featureClass as IDataset; if (pDataset == null) { return; } pDataset.CanDelete(); pDataset.Delete(); }
private void 除选中行ToolStripMenuItem_Click(object sender, EventArgs e) { bool flag = false; foreach (DataGridViewRow row in datagwSource.Rows) { if ((bool)row.Cells[0].EditedFormattedValue == true) { flag = true; break; } } if (!flag) { MessageBox.Show("没有选中行,无法删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } DialogResult result = MessageBox.Show("是否确定删除!", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { foreach (DataGridViewRow row in datagwSource.Rows) { if ((bool)row.Cells[0].EditedFormattedValue == true) { //IWorkspaceFactory Pwf = new FileGDBWorkspaceFactoryClass(); //pWorkspace = (IWorkspace)(Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0)); pWorkspace = GetWorkspace(comboBoxSource.Text); if (pWorkspace != null) { pWorkspace2 = (IWorkspace2)pWorkspace; if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, row.Cells[1].Value.ToString().Trim())) { IFeatureClass tmpfeatureclass; IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace; tmpfeatureclass = pFeatureWorkspace.OpenFeatureClass(row.Cells[1].Value.ToString().Trim()); IDataset set = tmpfeatureclass as IDataset; set.CanDelete(); set.Delete(); //listBoxDetail.Items.Add("删除了" + row.Cells[1].Value + "数据"); //listBoxDetail.Items.Add(" "); //listBoxDetail.Refresh(); } } DeleteSql(row.Cells[1].Value.ToString()); } } datagwSource.Rows.Clear(); ChangeGridView();//重新加载数据 MessageBox.Show("删除数据成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public static bool ReleaseInMemoryWorkspaceMemory(IWorkspace workspace) { if (null != workspace) { IDataset dataset = workspace as IDataset; if (null != dataset && dataset.CanDelete()) { dataset.Delete(); } } return(false); }
private static void deleteFeatureClass(IDataset ds) { if (ds.CanDelete()) { try { ds.Delete(); } catch (System.Runtime.InteropServices.COMException ex) { throw new System.IO.IOException(ex.Message + " " + System.IO.Path.Combine(((IWorkspace)ds).PathName, ds.Name)); } } }
public bool CanDelete() { IDataset dataset = this.Dataset; bool flag = false; try { flag = dataset.CanDelete(); } catch { } dataset = null; return(flag); }
public bool CanDelete() { try { IDataset dataset = this.Dataset; if (dataset != null) { bool flag = false; flag = dataset.CanDelete(); dataset = null; return(flag); } } catch { } return(false); }
public void DeleteFeatureDataset(string sFeatureDataset, string sConnectionFile) { IWorkspace pWorkspace = null; IEnumDataset pEnumDataset = null; IDataset pDataset = null; try { pWorkspace = ArcSdeWorkspaceFromFile(sConnectionFile); pEnumDataset = pWorkspace.get_Datasets(esriDatasetType.esriDTAny); pDataset = pEnumDataset.Next(); while (pDataset != null) { if (pDataset.Name.Contains(sFeatureDataset)) { if (pDataset.CanDelete()) { pDataset.Delete(); } else { throw new ApplicationException("Cannot delete dataset " + pDataset.Name); } } pDataset = pEnumDataset.Next(); } } catch (Exception ex) { throw ex; } finally { COMUtil.ReleaseObject(pDataset); COMUtil.ReleaseObject(pEnumDataset); COMUtil.ReleaseObject(pWorkspace); } }
//删除ROI private void ROIDataGridView_CellClick(object sender, DataGridViewCellEventArgs e) { try { if (e.ColumnIndex == 0 && e.RowIndex < ROIDataGridView.Rows.Count) { IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(ROIFileNames[e.RowIndex]); IDataset dataSet = featureClass as IDataset; if (dataSet.CanDelete()) { dataSet.Delete(); } else { throw new Exception("删除数据集出错。"); } ROIDataGridView.Rows.RemoveAt(e.RowIndex); ROINames.RemoveAt(e.RowIndex); ROIColors.RemoveAt(e.RowIndex); ROIFileNames.RemoveAt(e.RowIndex); m_mapControl.DeleteLayer(e.RowIndex); axTOCControl1.Refresh(); if (ROIDataGridView.Rows.Count < 1) { ChangeEditingIndex(-1); } else if (ROIDataGridView.Rows.Count < EditingIndex + 1) { ChangeEditingIndex(0); } } else if (e.RowIndex < ROIDataGridView.Rows.Count) { ChangeEditingIndex(e.RowIndex); } } catch (Exception err) { MessageBox.Show(err.ToString()); } }
private void KillExistingFeatureclass(string strFilename) { try { IGxCatalogDefaultDatabase Defaultgdb = ArcMap.Application as IGxCatalogDefaultDatabase; Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspace pWorkspace = workspaceFactory.OpenFromFile(Defaultgdb.DefaultDatabaseName.PathName, 0); IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace; IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pFeatureWorkspace.OpenFeatureClass(strFilename); IDataset pDataset = pFeatureLayer.FeatureClass as IDataset; if (pDataset.CanDelete()) { pDataset.Delete(); } } catch { } }
private bool DeleteTempFeatureClass() { try { IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(System.IO.Path.GetTempPath(), 0); IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(tempFeatureClassName); IDataset dataSet = featureClass as IDataset; if (dataSet.CanDelete()) { dataSet.Delete(); return(true); } return(false); } catch (Exception) { return(false); } }
/// <summary> /// 删除工作空间里的所有要素 /// </summary> /// <param name="workspace">工作空间</param> public void DeleteAllFeatureClass(IWorkspace workspace) { IEnumDataset enumDataset = workspace.get_Datasets(esriDatasetType.esriDTAny); enumDataset.Reset(); IDataset dataset = enumDataset.Next(); while (dataset != null) { if (dataset.CanDelete()) { if (dataset.Type == esriDatasetType.esriDTFeatureDataset) { IFeatureDataset featureDataset = dataset as IFeatureDataset; featureDataset.Delete(); } else { dataset.Delete(); } dataset = enumDataset.Next(); } } }
/// <summary> /// 将MDB的数据入到SDE中 xisheng 20110919 /// </summary> private void ImportMDBToSDE(string file, string outfilename, out int featurecount) { m_success = false;//初始化 try { string filepath = file.Substring(0, file.LastIndexOf("---")); string filename = file.Substring(file.LastIndexOf("-") + 1); //打开mdb文件所在的工作空间 ESRI.ArcGIS.Geodatabase.IWorkspaceFactory wf = new AccessWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWorkspaceGDB = wf.OpenFromFile(@filepath, 0) as IFeatureWorkspace; IWorkspace pWorkspaceGDB = pFeatureWorkspaceGDB as IWorkspace; // 创建源工作空间名称 IDataset sourceWorkspaceDataset = (IDataset)pFeatureWorkspaceGDB; IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDataset.FullName; //创建源数据集名称 //IFeatureClassName sourceFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName; IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass(); IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName; sourceDatasetName.WorkspaceName = sourceWorkspaceName; sourceDatasetName.Name = filename; //打开存在的工作空间,作为导入的空间; IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pTargetworkspace; //创建目标工作空间名称 IDataset targetWorkspaceDataset = (IDataset)pTargetworkspace; IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDataset.FullName; IWorkspace2 pWorkspace2 = pTargetworkspace as IWorkspace2; IFeatureDataset tmpfeaturedataset; //创建目标数据集名称 // IFeatureClassName targetFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName; //判断要素是否存在,若存在将删除源文件 if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureDataset, textBox.Text)) { tmpfeaturedataset = pFeatureWorkspace.OpenFeatureDataset(textBox.Text); if (text_prj.Text != "") { IGeoDatasetSchemaEdit pgeodataset = tmpfeaturedataset as IGeoDatasetSchemaEdit; if (pgeodataset.CanAlterSpatialReference) { pgeodataset.AlterSpatialReference(GetSpatialReferenceformFile(text_prj.Text)); } } } else { tmpfeaturedataset = CreateFeatureDataset(pTargetworkspace as IFeatureWorkspace, textBox.Text, text_prj.Text); } if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, outfilename)) { IFeatureClass tmpfeatureclass; tmpfeatureclass = pFeatureWorkspace.OpenFeatureClass(outfilename); IDataset tempset = tmpfeatureclass as IDataset; if (tempset.CanDelete()) { tempset.Delete(); } } IFeatureClassName targetFeatureClassName = new FeatureClassNameClass(); IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName; targetDatasetName.WorkspaceName = targetWorkspaceName; targetDatasetName.Name = outfilename; //目标数据集 IFeatureDatasetName outfeaturedatasetname = tmpfeaturedataset.FullName as IFeatureDatasetName; //打开输入的要素类以得到字段定义 ESRI.ArcGIS.esriSystem.IName sourceName = (ESRI.ArcGIS.esriSystem.IName)sourceFeatureClassName; IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();//打开源要素类 //验证字段名称,因为你正在不同类型的工作空间之间进行数据转换 //IFieldChecker fieldChecker = serverContext.CreateObject("esriGeoDatabase.FieldChecker") as IFieldChecker; IFieldChecker fieldChecker = new FieldCheckerClass(); IFields sourceFeatureClassFields = sourceFeatureClass.Fields; IFields targetFeatureClassFields; IEnumFieldError enumFieldError; //最重要的设置输入和验证工作空间 fieldChecker.InputWorkspace = pWorkspaceGDB; fieldChecker.ValidateWorkspace = pTargetworkspace; fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields); //遍历所有输出字段找到几何字段 IField geometryField; for (int i = 0; i < targetFeatureClassFields.FieldCount; i++) { if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry) { geometryField = targetFeatureClassFields.get_Field(i); //得到几何字段的几何定义 IGeometryDef geometryDef = geometryField.GeometryDef; //赋予几何定义一个空间索引格网数目和格网大小值 IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef; targetFCGeoDefEdit.GridCount_2 = 1; targetFCGeoDefEdit.set_GridSize(0, 0); //允许ArcGIS为数据加载确定一个有效的格网大小 targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference; //转换要素类中所有的要素 //IQueryFilter queryFilter = serverContext.CreateObject("esriGeoDatabase.QueryFilter") as IQueryFilter; ; QueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = ""; //加载要素类 //IFeatureDataConverter fctofc = serverContext.CreateObject("esriGeoDatabase.FeatureDataConverter") as IFeatureDataConverter; IFeatureDataConverter fctofc = new FeatureDataConverterClass(); IEnumInvalidObject enumErrors = fctofc.ConvertFeatureClass(sourceFeatureClassName, queryFilter, outfeaturedatasetname, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0); } } featurecount = sourceFeatureClass.FeatureCount(null); m_success = true; } catch (Exception ee) { m_success = false; m_strErr = ee.Message; featurecount = 0; } }
//** 功能描述: 获得要素类,如果已经存在的话,则直接打开,否则进行创建 //** 参数列表: pFeatWorkspace (IFeatureWorkspace) // sFeatClsName (String) // pFields (IFields) 某个要素类的字段 // pSpatialRefer (ISpatialReference)'如果需要改变创建的要素类的空间参考的话,就改变 // pDicField 更改字段的名称,key里边放的是原字段名称,item放的是目标字段名称 public static IFeatureClass CreatOrOpenFeatClsByName(ref IFeatureWorkspace pFeatWorkspace, string sFeatClsName, ref IFields pFields, ISpatialReference pSpatialRefer, Dictionary <string, string> pDicField) { IFeatureClass functionReturnValue = default(IFeatureClass); IFeatureClass pFeatCls = default(IFeatureClass); //Dim pGeoDataset As ESRI.ArcGIS.Geodatabase.IGeoDataset IFields pDesFields = default(IFields); IWorkspace2 pWorkspace2 = default(IWorkspace2); IWorkspace pWorkspace = default(IWorkspace); bool bHasExsit = false; IDataset pDataset = default(IDataset); try { //首选判断该数据集是否存在 if (pFeatWorkspace == null) { functionReturnValue = null; return(functionReturnValue); } pWorkspace = (IWorkspace)pFeatWorkspace; ////印骅 20081113 判断shapefile是否存在 if (pWorkspace.Type == esriWorkspaceType.esriFileSystemWorkspace) { bHasExsit = File.Exists(pWorkspace.PathName + "\\" + sFeatClsName + ".shp") && File.Exists(pWorkspace.PathName + "\\" + sFeatClsName + ".shx") && File.Exists(pWorkspace.PathName + "\\" + sFeatClsName + ".dbf"); } else { pWorkspace2 = (IWorkspace2)pFeatWorkspace; bHasExsit = pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, sFeatClsName); pFeatWorkspace = (IFeatureWorkspace)pWorkspace2; } if (bHasExsit == false) { pDesFields = GetFieldsByFields(pFields, ref pSpatialRefer, pDicField); IFeatureDataset pFeatureDataset = null; esriFeatureType pEnumFeatType = esriFeatureType.esriFTSimple; pFeatCls = CreateFeatCls(ref sFeatClsName, ref pFeatWorkspace, pDesFields, ref pFeatureDataset, ref pEnumFeatType, "shape"); } else { //因为在获取工作空间的时候已经删除了空间内可能存在的要素集和要素类,所以下面的语句实际上永远不会被执行 yh //如果要找的要素类存在的话,则打开 pFeatCls = pFeatWorkspace.OpenFeatureClass(sFeatClsName); pDataset = (IDataset)pFeatCls; if (pDataset.CanDelete()) { pDataset.Delete(); } //重新创建要素类 pDesFields = GetFieldsByFields(pFields, ref pSpatialRefer, pDicField); IFeatureDataset pFeatureDataset = null; esriFeatureType pEnumFeatType = esriFeatureType.esriFTSimple; pFeatCls = CreateFeatCls(ref sFeatClsName, ref pFeatWorkspace, pDesFields, ref pFeatureDataset, ref pEnumFeatType, "shape"); } functionReturnValue = pFeatCls; return(functionReturnValue); } catch (Exception ex) { MessageBoxEx.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); functionReturnValue = null; } return(functionReturnValue); }
/// <summary> /// Deletes the dataset if possible /// </summary> /// <remarks> /// - Checks for a shcema lock before deleting (CanDelete returns true even if the dataset is locked) /// - Returns true if the dataset was deleted, else false /// </remarks> private static bool DeleteDataset(IDataset ds) { ISchemaLock schemaLock = ds as ISchemaLock; if (ds.CanDelete() && (schemaLock != null)) { try { schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock); ds.Delete(); return true; } catch { schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); } } return false; }
/// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { Process process; ProcessStartInfo startInfo = new ProcessStartInfo(); //StreamWriter sm = new StreamWriter(ArcTimData.StaticClass.infoTable.Rows[0]["ModelPath"].ToString() + "\runTim.log"); string timMLFileName = this.prepareTimInputFile(); startInfo.FileName = ArcTimData.StaticClass.infoTable.Rows[0]["PythonPath"].ToString() + "\\python"; startInfo.Arguments = timMLFileName; startInfo.WindowStyle = ProcessWindowStyle.Maximized; startInfo.ErrorDialog = true; process = Process.Start(startInfo); Console.WriteLine("Waiting for 30 seconds for process to finish."); if (process.WaitForExit(18000000)) { Console.WriteLine("Process terminated."); } else { Console.WriteLine("TImed out waiting for process to end."); } for (int i = 0; i < ArcTimData.StaticClass.aqPropTable.Rows.Count; i++) { string modelpath = ArcTimData.StaticClass.infoTable.Rows[0]["ModelPath"].ToString(); string modelName = ArcTimData.StaticClass.infoTable.Rows[0]["ModelName"].ToString(); string filename = modelpath + "\\" + modelName + Convert.ToString(i + 1) + ".txt"; string outputfilename = modelpath + "\\" + modelName + Convert.ToString(i + 1) + ".aux"; //string outputfilename = ArcTim5PropertiesMenu.StaticClass.pathName + "\\" + "TimOut" + Convert.ToString(i + 1) + ".aux"; string checkName = modelName + Convert.ToString(i + 1); //string checkName = "TimOut" + Convert.ToString(i + 1); if (modelName.Length > 7) { checkName = modelName.Remove(6) + (i + 1); outputfilename = modelpath + "\\" + checkName + ".aux"; } int checkRaster = CheckforExisitingRaster(checkName); IMxDocument pMxDoc = GetMxDocument(m_application); IWorkspaceFactory pRasterWSF = new RasterWorkspaceFactory(); if (checkRaster >= 0) { IRasterWorkspace pRasterWS = pRasterWSF.OpenFromFile(modelpath, 0) as IRasterWorkspace; IRasterDataset pRasterDataset = pRasterWS.OpenRasterDataset(checkName); IDataset pDataset = pRasterDataset as IDataset; if (checkRaster >= 0) { pMxDoc.FocusMap.DeleteLayer(pMxDoc.FocusMap.get_Layer(checkRaster)); } if (pDataset.CanDelete()) { pDataset.Delete(); } } if (File.Exists(outputfilename) || Directory.Exists(modelpath + "\\" + checkName) || Directory.Exists(modelpath + "\\Info")) { if (File.Exists(outputfilename)) { File.Delete(outputfilename); } if (Directory.Exists(modelpath + "\\" + checkName)) { Directory.Delete(modelpath + "\\" + checkName, true); } if (Directory.Exists(modelpath + "\\Info")) { Directory.Delete(modelpath + "\\Info", true); } } readModelOutput(filename, checkName); } }
private void butOk_Click(object sender, EventArgs e) { if (this.CheckingInput()) { Application.DoEvents(); this.comboxlayer.Enabled = false; this.comboxFiled.Enabled = false; this.comboClss1.Enabled = false; this.comboClss2.Enabled = false; this.textBox1.Enabled = false; this.button1.Enabled = false; this.butOk.Enabled = false; this.progressBar1.Visible = true; this.progressBar1.Minimum = 0; ILayer layer = this.MapLayer[this.comboxlayer.SelectedIndex]; IDataset pDataSet = (layer as IFeatureLayer).FeatureClass as IDataset; //string outputDir = System.Environment.CurrentDirectory + "\\Default.gdb"; IWorkspace pWorkspace = Utilities.WorkspaceHelper.GetShapefileWorkspace(MainForm.outshape); // IEnumDataset pDataSetsEnum = pWorkspace.get_Datasets(esriDatasetType.esriDTAny); IDataset pDataTM = pDataSetsEnum.Next(); while (pDataTM != null) { if (pDataTM.Name == "temp") { if (pDataTM.CanDelete()) { pDataTM.Delete(); break; } else { MessageBox.Show("请检查是否处于打开状态!"); return; } } pDataTM = pDataSetsEnum.Next(); } ArcGISUtilities.CopyData((layer as IFeatureLayer).FeatureClass, pWorkspace, "temp"); IEnumDataset pEnumDS = pWorkspace.get_Datasets(esriDatasetType.esriDTAny); IFeatureClass featureClass = ArcGISUtilities.GetDatasetByName(pEnumDS, "temp") as IFeatureClass; IQueryFilter pQueryFilter = null; IFeatureCursor pFCursor = null; int index = featureClass.Fields.FindField(comboxFiled.Text); if (index < 0) { MessageBox.Show("请检查数据是否含分类码或检查编码文件.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } foreach (ListViewItem lvi in listView1.Items) { string code = lvi.Text; if (code.Substring(0, 1) == "0" || code.Substring(0, 1) == "1") { string temp = lvi.Text.Substring(2, 2); //一级类 if (temp == "00") { code = code.Substring(0, 2); pQueryFilter = new QueryFilterClass(); //pQueryFilter.WhereClause = "[" + comboxFiled.Text + "]" + " LIKE " + "\'" + code + "**" + "\'";//GeoDatase中 pQueryFilter.WhereClause = comboxFiled.Text + " LIKE " + "\'" + code + "__" + "\'"; pFCursor = featureClass.Update(pQueryFilter, false); IFeature pFeat = pFCursor.NextFeature(); while (pFeat != null) { pFeat.set_Value(index, lvi.Text); pFCursor.UpdateFeature(pFeat); pFeat = pFCursor.NextFeature(); } } //二级类 else if (temp.Substring(1, 1) == "0") { code = code.Substring(0, 3); pQueryFilter = new QueryFilterClass(); pQueryFilter.WhereClause = "[" + comboxFiled.Text + "]" + " LIKE " + "\'" + code + "*" + "\'"; pFCursor = featureClass.Update(pQueryFilter, false); IFeature pFeat = pFCursor.NextFeature(); while (pFeat != null) { pFeat.set_Value(index, lvi.Text); pFCursor.UpdateFeature(pFeat); pFeat = pFCursor.NextFeature(); } } } this.progressBar1.Value += 1; } //////////////////////////////////////////////////////////////////////////////////////////////////// Application.DoEvents(); this.progressBar1.Value = 70; IFeatureClass pFeatureClass = null; VectorOperation operation = new VectorOperation(); pFeatureClass = operation.Dissolv(featureClass, comboxFiled.Text, textBox1.Text.Trim(), this.textBox2.Text.Trim() , this.progressBar1); IFeatureLayer pLayer = new FeatureLayerClass { FeatureClass = pFeatureClass, Name = pFeatureClass.AliasName }; this.m_axMapControl.AddLayer(pLayer); this.m_axMapControl.ActiveView.Refresh(); //释放资源 if (pFCursor != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(pFCursor); } if (pQueryFilter != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(pQueryFilter); } if (featureClass != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(featureClass); } MessageBox.Show(pLayer.Name + "处理完成!"); base.Close(); } }
//下载为MDB文件 private void btn_ExportNDB_Click(object sender, EventArgs e) { pWorkspace = GetWorkspace(comboBoxSource.Text); if (pWorkspace == null) { MessageBox.Show("数据源空间不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } bool flag = false; //获取模板路径 string sourcefilename = Application.StartupPath + "\\..\\Template\\DATATEMPLATE.mdb"; foreach (DataGridViewRow row in datagwSource.Rows) { if ((bool)row.Cells[0].EditedFormattedValue == true) { flag = true; } } if (!flag) { MessageBox.Show("没有选中行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } SysCommon.CProgress vProgress = new SysCommon.CProgress("正在下载数据,请稍后"); try { if (File.Exists(sourcefilename))//原模板存在 { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "MDB数据|*.mdb"; dlg.OverwritePrompt = false; dlg.Title = "保存到MDB"; DialogResult result = MessageBox.Show("下载是否去掉前缀?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dlg.ShowDialog() == DialogResult.OK) { //初始化进度条 vProgress.EnableCancel = false; vProgress.ShowDescription = false; vProgress.FakeProgress = true; vProgress.TopMost = true; vProgress.ShowProgress(); Application.DoEvents(); //IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactoryClass(); //pWorkspace = (IWorkspace)(pWorkspaceFactory.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0)); //如果存在mdb,替换文件,则复制模板到指定路径 //如果存在mdb,不替换,则追加到这个文件 File.Copy(sourcefilename, dlg.FileName, true); string cellvalue = ""; IWorkspaceFactory Pwf = new AccessWorkspaceFactoryClass(); IWorkspace pws = (IWorkspace)(Pwf.OpenFromFile(dlg.FileName, 0)); IWorkspace2 pws2 = (IWorkspace2)pws; foreach (DataGridViewRow row in datagwSource.Rows) { if ((bool)row.Cells[0].EditedFormattedValue == true) { cellvalue = row.Cells[1].Value.ToString().Trim(); if (cellvalue.Contains(".")) { cellvalue = cellvalue.Substring(cellvalue.LastIndexOf(".") + 1); } if (result == DialogResult.Yes) { cellvalue = cellvalue.Substring(15); //去掉前缀 } pws2 = (IWorkspace2)pws; if (pws2.get_NameExists(esriDatasetType.esriDTFeatureClass, cellvalue)) { IFeatureClass tmpfeatureclass; IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pws; tmpfeatureclass = pFeatureWorkspace.OpenFeatureClass(cellvalue); IDataset set = tmpfeatureclass as IDataset; set.CanDelete(); set.Delete(); flag = true; } IFeatureDataConverter_ConvertFeatureClass(pWorkspace, pws, row.Cells[1].Value.ToString().Trim(), cellvalue); } } vProgress.Close(); MessageBox.Show("下载成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Activate(); } } } catch (Exception ex) { vProgress.Close(); MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Activate(); } }
//栅格数据入库到GDB数据库的方法 private void ImportRasterToNewWorkSpace(string file, string outfilename) { try { string ExportFileShortName = outfilename; if (file == "") { return; } int Index = file.LastIndexOf("\\"); string ImportFileName = file.Substring(Index + 1); string ImportFilePath = System.IO.Path.GetDirectoryName(file); //打开存在的GDB工作空间 //IWorkspaceFactory Pwf = new FileGDBWorkspaceFactoryClass(); //IWorkspace pWorkspace = Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0); IWorkspace pWorkspace = GetWorkspace(comboBoxSource.Text); IWorkspace2 pWorkspace2 = (IWorkspace2)pWorkspace; //判断要素是否存在,若存在将删除源文件 if (pWorkspace2.get_NameExists(esriDatasetType.esriDTRasterDataset, ImportFileName)) { if (m_newfile == true) { IRasterWorkspaceEx pRWs = pWorkspace as IRasterWorkspaceEx; IDataset pDataset = pRWs.OpenRasterDataset(ImportFileName) as IDataset; pDataset.CanDelete(); pDataset.Delete(); pDataset = null; } else { MessageBox.Show("存在相同文件名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); m_success = false; return; } } //IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactoryClass(); //IWorkspace pWs = pWorkspaceFactory.OpenFromFile(ImportFilePath, 0); //IRasterDataset pRasterDs = null; //IRasterWorkspace pRasterWs; //IRasterWorkspaceEx pRasterEx=pWs as IRasterWorkspaceEx; //pRasterWs = pWs as IRasterWorkspace; //pRasterDs = pRasterWs.OpenRasterDataset(ImportFileName); //ISaveAs2 saveAs2 = (ISaveAs2)pRasterDs; ITrackCancel pTrackCancel = new TrackCancelClass(); IRasterCatalogLoader pRasterload = new RasterCatalogLoaderClass(); pRasterload.Workspace = pWorkspace; pRasterload.EnableBuildStatistics = true; pRasterload.StorageDef = new RasterStorageDefClass(); pRasterload.StorageDef.CompressionType = esriRasterCompressionType.esriRasterCompressionLZ77; pRasterload.StorageDef.PyramidLevel = 9; pRasterload.StorageDef.CompressionQuality = 50; pRasterload.StorageDef.TileHeight = 128; pRasterload.StorageDef.TileWidth = 128; pRasterload.Projected = true; //加载栅格数据到catalog方法 pRasterload.Load(comboBoxCatalog.Text.Trim(), ImportFilePath, pTrackCancel); //单独导入栅格数据 #region //IRasterStorageDef rasterStorageDef = new RasterStorageDefClass(); //IRasterStorageDef2 rasterStorageDef2 = (IRasterStorageDef2)rasterStorageDef; ////栅格压缩数据格式设定 //string[] str = file.Split('.'); //switch (str[1].ToLower()) //{ // case "jpg": // rasterStorageDef2.CompressionType = esriRasterCompressionType.esriRasterCompressionJPEG2000; // break; // case "sid":case "img": // rasterStorageDef2.CompressionType = esriRasterCompressionType.esriRasterCompressionLZ77; // break; //} //rasterStorageDef2.CompressionQuality = 50; //rasterStorageDef2.Tiled = true; //rasterStorageDef2.TileHeight = 128; //rasterStorageDef2.TileWidth = 128; //saveAs2.SaveAsRasterDataset(outfilename, pWorkspace, "gdb", rasterStorageDef2); #endregion m_success = true; } catch (Exception ex) { m_success = false; } }
public bool DeleteTemporarSource(string resultTable, string lineFeatureClass) { IWorkspace2 wsp2 = (IWorkspace2)calcWorkspace; IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)calcWorkspace; try { var datasets = calcWorkspace.get_Datasets(esriDatasetType.esriDTTable); IDataset tabledataset = datasets.Next(); if (tabledataset != null) { while (tabledataset != null) { if (!tabledataset.Name.Equals(resultTable)) { tabledataset = datasets.Next(); continue; } if (!tabledataset.CanDelete()) { throw new MilSpaceCanotDeletePrifileCalcTable(resultTable, MilSpaceConfiguration.ConnectionProperty.TemporaryGDBConnection); } tabledataset.Delete(); break; } } //Delete temprorary Feature class (Profile lites) datasets = calcWorkspace.get_Datasets(esriDatasetType.esriDTFeatureClass); if (tabledataset != null) { while (tabledataset != null) { if (!tabledataset.Name.Equals(lineFeatureClass)) { tabledataset = datasets.Next(); continue; } if (!tabledataset.CanDelete()) { throw new MilSpaceCanotDeletePrifileCalcTable(lineFeatureClass, MilSpaceConfiguration.ConnectionProperty.TemporaryGDBConnection); } tabledataset.Delete(); break; } } return(true); } catch (MilSpaceCanotDeletePrifileCalcTable ex) { //TODO: add logging throw; } catch (Exception ex) { //TODO: add logging } return(false); }
string m_strErr; //错误信息提醒 //SHP数据入库到GDB数据库的方法 private void ImportFeatureClassToNewWorkSpace(string filename, string outfilename) { //try //{ m_success = false; //初始化 string ImportShapeFileName = filename; string ExportFileShortName = outfilename; if (ImportShapeFileName == "") { return; } string ImportFileShortName = System.IO.Path.GetFileNameWithoutExtension(ImportShapeFileName); string ImportFilePath = System.IO.Path.GetDirectoryName(ImportShapeFileName); //打开存在的工作空间,作为导入的空间 IWorkspaceFactory Pwf = new FileGDBWorkspaceFactoryClass(); //IWorkspace pWorkspace = Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0); // IWorkspace2 pWorkspace2 =(IWorkspace2)(Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0)); IWorkspace pWorkspace = GetWorkspace(comboBoxSource.Text); if (pWorkspace == null) { m_strErr = "数据源未找到"; m_success = false; return; } string username = GetSourceUser(comboBoxSource.Text); if (username.Trim() != "") { ExportFileShortName = username + "." + ExportFileShortName; } IWorkspace2 pWorkspace2 = pWorkspace as IWorkspace2; //判断要素是否存在,若存在将删除源文件 if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, ExportFileShortName)) { if (m_newfile == true) { IFeatureClass tmpfeatureclass; IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace; tmpfeatureclass = pFeatureWorkspace.OpenFeatureClass(ExportFileShortName); IDataset set = tmpfeatureclass as IDataset; fdr.DeleteSql(ExportFileShortName); set.CanDelete(); set.Delete(); } else { //MessageBox.Show("存在相同文件名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); m_strErr = "存在相同文件名"; m_success = false; return; } } IWorkspaceName pInWorkspaceName; IFeatureDatasetName pOutFeatureDSName; IFeatureClassName pInFeatureClassName; IDatasetName pInDatasetName; IFeatureClassName pOutFeatureClassName; IDatasetName pOutDatasetName; long iCounter; IFields pOutFields, pInFields; IFieldChecker pFieldChecker; IField pGeoField; IGeometryDef pOutGeometryDef; IGeometryDefEdit pOutGeometryDefEdit; IName pName; IFeatureClass pInFeatureClass; IFeatureDataConverter pShpToClsConverter; IEnumFieldError pEnumFieldError = null; //得到一个输入SHP文件的工作空间, pInWorkspaceName = new WorkspaceNameClass(); pInWorkspaceName.PathName = ImportFilePath; pInWorkspaceName.WorkspaceFactoryProgID = "esriCore.ShapefileWorkspaceFactory.1"; //创建一个新的要素类名称,目的是为了以来PNAME接口的OPEN方法打开SHP文件 pInFeatureClassName = new FeatureClassNameClass(); pInDatasetName = (IDatasetName)pInFeatureClassName; pInDatasetName.Name = ImportFileShortName; pInDatasetName.WorkspaceName = pInWorkspaceName; //打开一个SHP文件,将要读取它的字段集合 pName = (IName)pInFeatureClassName; pInFeatureClass = (IFeatureClass)pName.Open(); //通过FIELDCHECKER检查字段的合法性,为输入要素类获得字段集合 pInFields = pInFeatureClass.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; } } //得到几何字段的几何定义 pOutGeometryDef = pGeoField.GeometryDef; //设置几何字段的空间参考和网格 pOutGeometryDefEdit = (IGeometryDefEdit)pOutGeometryDef; pOutGeometryDefEdit.GridCount_2 = 1; pOutGeometryDefEdit.set_GridSize(0, 1500000); //创建一个新的要素类名称作为可用的参数 pOutFeatureClassName = new FeatureClassNameClass(); pOutDatasetName = (IDatasetName)pOutFeatureClassName; pOutDatasetName.Name = ExportFileShortName; //创建一个新的数据集名称作为可用的参数 pOutFeatureDSName = (IFeatureDatasetName) new FeatureDatasetName(); //如果参数的值是NULL,说明要创建独立要素类 //创建一个不存在的要素集合pFDN,通过它将IFeatureClassName和工作空间连接起来,而ConvertFeatureClass函数并不使用该变量作为参数, IFeatureDatasetName pFDN = new FeatureDatasetNameClass(); IDatasetName pDN = (IDatasetName)pFDN; IDataset pDS = (IDataset)pWorkspace; pDN.WorkspaceName = (IWorkspaceName)pDS.FullName; pOutFeatureClassName.FeatureDatasetName = (IDatasetName)pFDN; //将pOutFeatureDSName设置为Null,将它做为参数给ConvertFeatureClass函数,因为IFeatureClassName本身已经和工作空间关联了,生成的 //要素类在工作空间的根目录下,即独立要素类 pOutFeatureDSName = null; //开始导入 if (InsertIntoDatabase(ExportFileShortName)) { pShpToClsConverter = new FeatureDataConverterClass(); pShpToClsConverter.ConvertFeatureClass(pInFeatureClassName, null, pOutFeatureDSName, pOutFeatureClassName, pOutGeometryDef, pOutFields, "", 1000, 0); //MessageBox.Show("导入成功", "提示"); m_success = true; } //} //catch //{ // m_success = false; //} }
//将mdb中要素类转换复制到GDB数据库中 private void ImportMDBToGDB(string file, string outfilename) { m_success = false;//初始化 try { string filepath = file.Substring(0, file.LastIndexOf("---")); string filename = file.Substring(file.LastIndexOf("-") + 1); //打开mdb文件所在的工作空间 ESRI.ArcGIS.Geodatabase.IWorkspaceFactory wf = new AccessWorkspaceFactory(); IFeatureWorkspace pFeatureWorkspaceMDB = wf.OpenFromFile(@filepath, 0) as IFeatureWorkspace; IWorkspace pWorkspaceMDB = pFeatureWorkspaceMDB as IWorkspace; // 创建源工作空间名称 IDataset sourceWorkspaceDataset = (IDataset)pWorkspaceMDB; IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDataset.FullName; //创建源数据集名称 //IFeatureClassName sourceFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName; IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass(); IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName; sourceDatasetName.WorkspaceName = sourceWorkspaceName; sourceDatasetName.Name = filename; //打开存在的工作空间,作为导入的空间 IWorkspaceFactory Pwf = new FileGDBWorkspaceFactoryClass(); //IWorkspace pWorkspaceGDB = Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0); //IWorkspace2 pWorkspace2 = (IWorkspace2)(Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0)); IWorkspace pWorkspaceGDB = GetWorkspace(comboBoxSource.Text); if (pWorkspaceGDB == null) { m_strErr = "数据源未找到"; m_success = false; return; } string username = GetSourceUser(comboBoxSource.Text); if (username.Trim() != "") { outfilename = username + "." + outfilename; } IWorkspace2 pWorkspace2 = pWorkspaceGDB as IWorkspace2; IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceGDB; //创建目标工作空间名称 IDataset targetWorkspaceDataset = (IDataset)pWorkspaceGDB; IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDataset.FullName; //创建目标数据集名称 // IFeatureClassName targetFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName; //判断要素是否存在,若存在将删除源文件 if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, outfilename)) { if (m_newfile == true) { IFeatureClass tmpfeatureclass; tmpfeatureclass = pFeatureWorkspace.OpenFeatureClass(outfilename); IDataset set = tmpfeatureclass as IDataset; fdr.DeleteSql(filename); set.CanDelete(); set.Delete(); } else { m_strErr = "存在相同文件名"; m_success = false; return; } } IFeatureClassName targetFeatureClassName = new FeatureClassNameClass(); IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName; targetDatasetName.WorkspaceName = targetWorkspaceName; targetDatasetName.Name = outfilename; //打开输入的要素类以得到字段定义 ESRI.ArcGIS.esriSystem.IName sourceName = (ESRI.ArcGIS.esriSystem.IName)sourceFeatureClassName; IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();//打开源要素类 //验证字段名称,因为你正在不同类型的工作空间之间进行数据转换 //IFieldChecker fieldChecker = serverContext.CreateObject("esriGeoDatabase.FieldChecker") as IFieldChecker; IFieldChecker fieldChecker = new FieldCheckerClass(); IFields sourceFeatureClassFields = sourceFeatureClass.Fields; IFields targetFeatureClassFields; IEnumFieldError enumFieldError; //最重要的设置输入和验证工作空间 fieldChecker.InputWorkspace = pWorkspaceMDB; fieldChecker.ValidateWorkspace = pWorkspaceGDB; fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields); //遍历所有输出字段找到几何字段 IField geometryField; for (int i = 0; i < targetFeatureClassFields.FieldCount; i++) { if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry) { geometryField = targetFeatureClassFields.get_Field(i); //得到几何字段的几何定义 IGeometryDef geometryDef = geometryField.GeometryDef; //赋予几何定义一个空间索引格网数目和格网大小值 IGeometryDefEdit targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef; targetFCGeoDefEdit.GridCount_2 = 1; targetFCGeoDefEdit.set_GridSize(0, 0); //允许ArcGIS为数据加载确定一个有效的格网大小 targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference; //转换要素类中所有的要素 //IQueryFilter queryFilter = serverContext.CreateObject("esriGeoDatabase.QueryFilter") as IQueryFilter; ; QueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = ""; //加载要素类 //IFeatureDataConverter fctofc = serverContext.CreateObject("esriGeoDatabase.FeatureDataConverter") as IFeatureDataConverter; if (InsertIntoDatabase(outfilename))//更新数据库 { IFeatureDataConverter fctofc = new FeatureDataConverterClass(); IEnumInvalidObject enumErrors = fctofc.ConvertFeatureClass(sourceFeatureClassName, queryFilter, null, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0); } } } m_success = true; } catch { m_success = false; m_strErr = ""; } }