转自wbaolong原文 ArcEngine控制台应用程序

控制台应用程序相比其他应用程序,更加简单,简化了许多冗余,可以让我们更加关注于本质的东西。
现在让我们看一看ArcGIS Engine的控制台应用程序吧!

一、首先是许可绑定:
  1、运行时环境的绑定

ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop);

2、AO的许可级别

IAoInitialize aoInitialize = new AoInitializeClass();
esriLicenseStatus licenseStatus = aoInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeStandard);
if (licenseStatus != esriLicenseStatus.esriLicenseCheckedOut)
{
Console.WriteLine("Unable to check-out an ArcInfo license, error code is {0}", licenseStatus);
return;
}

二、接下来就可以写我们的程序啦。

    using System;
using System.IO;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry; namespace CursorDemo
{
public class CursorDemo
{
public static void Main(string[] args)
{
#region Licensing
ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop);
// Set up the licencing. NOTE: This sample assumes that you are using ArcInfo Desktop.
// You will need to adjust this code if using ArcEngine or ArcEditor.
IAoInitialize aoInitialize = new AoInitializeClass();
esriLicenseStatus licenseStatus = aoInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeStandard);
if (licenseStatus != esriLicenseStatus.esriLicenseCheckedOut)
{
Console.WriteLine("Unable to check-out an ArcInfo license, error code is {0}", licenseStatus);
return;
}
#endregion // If test data exists from a previous run, delete it.
if (Directory.Exists("CursorDemo.gdb"))
{
Directory.Delete("CursorDemo.gdb", true);
} // Copy the test data from this section's Data directory.
Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
IWorkspaceName sourceWorkspaceName = new WorkspaceNameClass
{
PathName = @"..\..\..\Data\CursorDemo.gdb",
WorkspaceFactoryProgID = "esriDataSourcesGDB.FileGDBWorkspaceFactory"
};
IWorkspaceName copiedWorkspaceName = null;
workspaceFactory.Copy(sourceWorkspaceName, Environment.CurrentDirectory, out copiedWorkspaceName); // Open the copied data.
IName copiedName = (IName)copiedWorkspaceName;
IWorkspace workspace = (IWorkspace)copiedName.Open();
IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace; // Open the two feature classes used in this demo.
IFeatureClass parcelsFeatureClass = featureWorkspace.OpenFeatureClass("Parcels");
IFeatureClass pipesFeatureClass = featureWorkspace.OpenFeatureClass("Pipes"); // The first demo, SearchCursorDemo, will display the Parcel IDs of all residential
// parcels within a certain extent.
SearchCursorDemo(parcelsFeatureClass); // The second demo, UpdateCursorDemo, will change the all parcels zoned as "Manufacturing"
// to "Commercial".
UpdateCursorDemo(workspace, parcelsFeatureClass); // The third demo, InsertCursorDemo, will create one hundred new pipe features using
// an insert cursor.
InsertCursorDemo(workspace, pipesFeatureClass); // Shutdown the licensing.
aoInitialize.Shutdown();
} /// <summary>
/// This sample queries a feature class of parcels, finding the Parcel IDs of all residential
/// features that are within a given extent.
/// </summary>
/// <param name="featureClass">The feature class to query.</param>
private static void SearchCursorDemo(IFeatureClass featureClass)
{
// Create an envelope that will define the spatial extent of the query.
IEnvelope envelope = new EnvelopeClass();
envelope.PutCoords(, , , ); // Create a new spatial filter.
ISpatialFilter spatialFilter = new SpatialFilterClass
{
Geometry = envelope,
GeometryField = featureClass.ShapeFieldName,
SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects,
SubFields = "Parcel_ID",
WhereClause = "ZONING_S = 'R'"
}; // Find the index of the Parcel_ID field. This is required to display the query results.
int parcelIdIndex = featureClass.FindField("Parcel_ID"); using (ComReleaser comReleaser = new ComReleaser())
{
// Query the feature class to get a feature cursor. We can use a recycling
// cursor because we're only going to be reading the data.
IFeatureCursor featureCursor = featureClass.Search(spatialFilter, true);
comReleaser.ManageLifetime(featureCursor); // Iterate through the query results.
IFeature feature = null;
while ((feature = featureCursor.NextFeature()) != null)
{
// Display the current feature's Parcel ID.
Console.WriteLine("Parcel found: {0}", feature.get_Value(parcelIdIndex));
}
// Display the number of feature matching the query.
Console.WriteLine("Parcels found: {0}", featureClass.FeatureCount(spatialFilter));
}
} /// <summary>
/// This sample re-zones all "Manufacturing" parcels as "Commercial".
/// </summary>
/// <param name="workspace">The workspace containing the feature class.</param>
/// <param name="featureClass">The feature class to update.</param>
private static void UpdateCursorDemo(IWorkspace workspace, IFeatureClass featureClass)
{
// Create a new query filter for the update.
IQueryFilter queryFilter = new QueryFilterClass { WhereClause = "ZONING_S = 'M'" }; // Display the feature's zoned as Manufacturing.
Console.WriteLine("Parcel found zoned as Manufacturing: {0}", featureClass.FeatureCount(queryFilter)); // Find the index of the Zoning_S field. This is required for the update.
int zoningIndex = featureClass.FindField("ZONING_S"); // Start a new edit session and edit operation.
IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;
workspaceEdit.StartEditing(true);
workspaceEdit.StartEditOperation(); using (ComReleaser comReleaser = new ComReleaser())
{
// Query the feature class to get a feature cursor. Since we are performing
// updates, we should use a non-recycling cursor.
IFeatureCursor featureCursor = featureClass.Update(queryFilter, false);
comReleaser.ManageLifetime(featureCursor); try
{
// Iterate through the query results.
IFeature feature = null;
while ((feature = featureCursor.NextFeature()) != null)
{
// Change the feature's ZONING_S value to "B" (the code for Business/Commercial).
feature.set_Value(zoningIndex, "B"); // Update the feature.
featureCursor.UpdateFeature(feature);
} // All of the features were successfully updated; stop the edit operation
// and stop the edit session, saving the changes made in edit operations.
workspaceEdit.StopEditOperation();
workspaceEdit.StopEditing(true);
}
catch (COMException)
{
// An error occurred while editing. Abort the edit operation and stop the
// edit session, discarding any changes made in edit operations.
workspaceEdit.AbortEditOperation();
workspaceEdit.StopEditing(false);
} // Display the feature's zoned as Manufacturing after update.
Console.WriteLine("Parcel found zoned as Manufacturing after update: {0}", featureClass.FeatureCount(queryFilter));
}
} /// <summary>
/// This sample uses an insert cursor to create one hundred new pipe features.
/// </summary>
/// <param name="workspace">The workspace containing the feature class.</param>
/// <param name="featureClass">The feature class to insert new features into.</param>
private static void InsertCursorDemo(IWorkspace workspace, IFeatureClass featureClass)
{
// Find the index of the "Contractor" field. This will be edited in the new features.
int contractorIndex = featureClass.FindField("CONTRACTOR"); // Put the feature class into "load-only" mode. In a File GDB, this will disable spatial
// and attribute indexing, improving performance for data loading.
IFeatureClassLoad featureClassLoad = (IFeatureClassLoad)featureClass;
featureClassLoad.LoadOnlyMode = true; // Start an edit session and edit operation.
IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;
workspaceEdit.StartEditing(true);
workspaceEdit.StartEditOperation(); // Open the two text files containing the contractor's data.
using (StreamReader geometryReader = new StreamReader(@"PipeGeo.csv"))
using (StreamReader attributeReader = new StreamReader(@"PipeAttr.csv"))
using (ComReleaser comReleaser = new ComReleaser())
{
// Create a new insert cursor with buffering.
IFeatureCursor featureCursor = featureClass.Insert(true);
comReleaser.ManageLifetime(featureCursor); // Create a feature buffer. This will store the values common to every
// feature to be installed.
IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
comReleaser.ManageLifetime(featureBuffer);
featureBuffer.set_Value(contractorIndex, "B Pierce"); try
{
while (!geometryReader.EndOfStream && !attributeReader.EndOfStream)
{
// Read the next line from each text file.
String geometryData = geometryReader.ReadLine();
String attributeData = attributeReader.ReadLine(); // Set the geometry and attribute values of the feature buffer.
featureBuffer.Shape = ConstructGeometryFromString(geometryData);
PopulateAttributeValues(featureBuffer, attributeData); // Insert a new feature using the feature buffer.
featureCursor.InsertFeature(featureBuffer);
} // Flush the cursor.
featureCursor.Flush(); // All of the features were successfully inserted; stop the edit operation
// and stop the edit session, saving the changes made in edit operations.
workspaceEdit.StopEditOperation();
workspaceEdit.StopEditing(true);
}
catch (COMException)
{
// An error occurred while editing. Abort the edit operation and stop the
// edit session, discarding any changes made in edit operations.
workspaceEdit.AbortEditOperation();
workspaceEdit.StopEditing(false);
}
} // Take the class out of load-only mode.
featureClassLoad.LoadOnlyMode = false;
} /// <summary>
/// This method converts a comma-delimited set of numeric values into a polyline.
/// </summary>
/// <param name="input">A string of comma-delimited numeric values.</param>
/// <returns>A polyline.</returns>
private static IGeometry ConstructGeometryFromString(String input)
{
// Split the input string into individual values.
String[] inputValues = input.Split(new char[] { ',' }); // Create a new polyline.
IPolyline polyline = new PolylineClass();
IGeometryCollection geometryCollection = (IGeometryCollection)polyline; // Each set of four values represents one segment of a polyline.
int segmentCount = inputValues.Length / ;
int inputValuePosition = ;
for (int i = ; i < segmentCount; i++)
{
// This value is required for geometry construction.
object missingType = Type.Missing; // Construct the segment.
IPoint fromPoint = new PointClass
{
X = Double.Parse(inputValues[inputValuePosition++]),
Y = Double.Parse(inputValues[inputValuePosition++])
};
IPoint toPoint = new PointClass
{
X = Double.Parse(inputValues[inputValuePosition++]),
Y = Double.Parse(inputValues[inputValuePosition++])
};
IPath path = new PathClass();
IPointCollection pointCollection = (IPointCollection)path;
pointCollection.AddPoint(fromPoint, ref missingType, ref missingType);
pointCollection.AddPoint(toPoint, ref missingType, ref missingType); // Add the segment to the collection.
geometryCollection.AddGeometry(path, ref missingType, ref missingType);
} // Return the constructed polyline.
return polyline;
} /// <summary>
/// Populates the inbound feature buffer with the comma-delimited values
/// in the input string.
/// </summary>
/// <param name="featureBuffer">The feature buffer to populate.</param>
/// <param name="input">A string containing attribute values.</param>
private static void PopulateAttributeValues(IFeatureBuffer featureBuffer, String input)
{
// Split the input string into individual values.
String[] inputValues = input.Split(new char[] { ',' }); // Set the values of the Date_Installed, material and diameter fields.
// For the sake of simplicity, we'll hard-code the values here.
featureBuffer.set_Value(, inputValues[]);
featureBuffer.set_Value(, inputValues[]);
featureBuffer.set_Value(, inputValues[]);
}
}
}

ArcEngine控制台应用程序的更多相关文章

  1. asp.net mvc引用控制台应用程序exe

    起因:有一个控制台应用程序和一个web程序,web程序想使用exe程序的方法,这个时候就需要引用exe程序. 报错:使用web程序,引用exe程序 ,vs调试没有问题,但是部署到iis就报错,如下: ...

  2. Win32程序和控制台应用程序的项目互转设置

    一般情况下,如果是windows程序,那么WinMain是入口函数,在VS2010中新建项目为"win32项目" 如果是dos控制台程序,那么main是入口函数,在VS2010中新 ...

  3. 【C#】1.2 控制台应用程序学习要点

    分类:C#.VS2015 创建日期:2016-06-14 教材:十二五国家级规划教材<C#程序设计及应用教程>(第3版) 一.要点概述 <C#程序设计及应用教程>(第3版)的第 ...

  4. 【C++】第1章 在VS2015中用C++编写控制台应用程序

    分类:C++.VS2015 创建日期:2016-06-12 一.简介 看到不少人至今还在用VC 6.0开发工具学习C++,其实VC 6.0开发工具早就被淘汰了.这里仅介绍学习C++时推荐使用的两种开发 ...

  5. c#取得控制台应用程序根目录

    1.取得控制台应用程序的根目录方法 方法1.Environment.CurrentDirectory 取得或设置当前工作目录的完整限定路径方法2.AppDomain.CurrentDomain.Bas ...

  6. Web应用程序或者WinForm程序 调用 控制台应用程序及参数传递

    有时候在项目中,会调用一个控制台应用程序去处理一些工作.那在我们的程序中要怎么样做才能调用一个控制台应用程序并将参数传递过去,控制台程序执行完后,我们的程序又怎样获取返回值?代码如下:调用代码:    ...

  7. vc2010 win32 控制台应用程序中文乱码

    vc2010 win32 控制台应用程序中文乱码 在 vc2010 上用 win32 控制台程序写些测试代码调用 windows api ,处理错误信息时,发现用 wprintf 输出的错误信息出现了 ...

  8. c# 隐藏 控制台应用程序

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  9. 如何编写一个编译c#控制台应用程序的批处理程序

    如何编写一个编译c#控制台应用程序的批处理程序 2011-03-22 18:14 dc毒蘑菇 | 浏览 579 次 最近在网上看了一个教程,是学C#的,但是我的机子上装不上vs,所以想写一个批处理来编 ...

随机推荐

  1. [Apple开发者帐户帮助]九、参考(6)支持的功能(watchOS)

    watchOS扩展可用的功能取决于您的程序成员身份. 注意:对于watchOS应用程序目标,可用的功能是应用程序组和后台模式,并且不依赖于您的程序成员身份. 能力 ADP 企业 Apple开发者 应用 ...

  2. 【洛谷3321_BZOJ3992】[SDOI2015]序列统计(原根_多项式)

    题目: 洛谷3321 分析: 一个转化思路比较神(典型?)的题-- 一个比较显然的\(O(n^3)\)暴力是用\(f[i][j]\)表示选了\(i\)个数,当前积在模\(m\)意义下为\(j\)的方案 ...

  3. 解决gradle project refresh failed: protocol family unavailable问题的几种方法

    Android Studio从版本1.5更新到2.1之后,打开Android Studio一直提示: gradle project refresh failed: protocol family un ...

  4. C# asp.net repeater实现排序功能,自动排序,点击头部排序,点击列排序

    在网上看到好多关于repeater排序的,自己动手用了,发现一些问题,贴源码后把发现的问题以及解决方法给出 repeater实现排序功能(单击升序排列,再单击降序排列).原理很简单,在<TD&g ...

  5. [ BZOJ 2134 ] 单选错位

    \(\\\) \(Description\) 一共\(N​\)道题目,第\(i​\)道题有\(A_i​\)个选项,现在有一个人做完了所有题目,但将每一道题的答案都写到了下一道题的位置\((​\)第\( ...

  6. HDU_3549_网络流(最大流)

    Flow Problem Time Limit: 5000/5000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)Tota ...

  7. HDU_5723_最小生成树+任意两点距离的期望

    Abandoned country Time Limit: 8000/4000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others ...

  8. mysql 如何用命令清除表数据,让表数据索引是从0开始呢?

    truncate MYTABLE 这样就可以了 其实这个命令就相当于删除表再建 所有的数据都还原 可以使用工具来完成这个操作 右键单击要操作的表,选择Turncale Table 执行查询语句,数据就 ...

  9. 11.11如何卖到一个亿:从0到1的电商爆品打造术 电子书 PDF

    内容转自:https://download.csdn.net/download/chenyao1994/11191034 下载地址:https://pan.baidu.com/s/1uQ1cjm9QH ...

  10. Python面向对象----继承, 重载

    1. 面向对象三大特性之继承. 继承的便捷是子类可以直接调用父类里面的方法和属性.(在强类型语言里面是只能调用公有成员), 不用重复的造轮子. 减少程序猿的负担.实现多态等上层结构 2. 父类代码 3 ...