using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OSGeo.OGR;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
[DllImport("gdal201.dll", EntryPoint = "OGR_F_GetFieldAsString", CallingConvention = CallingConvention.Cdecl)]
public extern static System.IntPtr OGR_F_GetFieldAsString(HandleRef handle, int i);
static void Main(string[] args)
{
ReadVectorFile();
}
static void ReadVectorFile()
{
// 为了支持中文路径,请添加下面这句代码
OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","YES");
// 为了使属性表字段支持中文,请添加下面这句
OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "GB18030");
string strVectorFile = "D:\\dq.shp"; //在这里修改你的文件路径
// 注册所有的驱动
Ogr.RegisterAll();
//打开数据
DataSource ds = Ogr.Open(strVectorFile,0);
if( ds == null )
{
Console.WriteLine( "打开文件【{0}】失败!", strVectorFile );
return;
}
Console.WriteLine( "打开文件【{0}】成功!", strVectorFile );
int iLayerCount = ds.GetLayerCount();
Layer oLayer = ds.GetLayerByIndex( 0 );
if( oLayer == null )
{
Console.WriteLine( "获取第{0}个图层失败!\n", 0 );
return;
}
oLayer.ResetReading();
Console.WriteLine( "属性表结构信息:");
FeatureDefn oDefn = oLayer.GetLayerDefn();
int iFieldCount =oDefn.GetFieldCount();
for( int iAttr = 0; iAttr <iFieldCount; iAttr++ )
{
FieldDefn oField =oDefn.GetFieldDefn( iAttr );
Console.WriteLine( "{0}:{1} ({2}.{3})", oField.GetNameRef(),
oField.GetFieldTypeName(oField.GetFieldType()),
oField.GetWidth(),oField.GetPrecision() );
}
// 输出图层中的要素个数
Console.WriteLine( "要素个数 = {0}", oLayer.GetFeatureCount(0) );
Feature oFeature = null;
// 下面开始遍历图层中的要素
while( (oFeature =oLayer.GetNextFeature()) != null )
{
Console.WriteLine("当前处理第{0}个: \n属性值:" ,oFeature.GetFID());
// 获取要素中的属性表内容
for (int iField = 0;iField<iFieldCount; iField++)
{
FieldDefn oFieldDefn= oDefn.GetFieldDefn(iField);
FieldType type =oFieldDefn.GetFieldType();
switch (type)
{
case FieldType.OFTString:
IntPtr pchar = OGR_F_GetFieldAsString(OSGeo.OGR.Feature.getCPtr(oFeature), iField);//这里用的OGR_F_GetFieldAsString是用的第一步用的OGR_F_GetFieldAsString函数(记住第二歩不能是CP936,不然还是读不了,应是GB18030)
//注意“filed2”为字段的位置号,为INT,不能为字符串,不然识别不了
string sFValue2 = Marshal.PtrToStringAnsi(pchar);//在这里你可看到可爱的汉字,哈哈
Console.WriteLine("{0}\t", sFValue2);
break;
case FieldType.OFTReal:
Console.WriteLine("{0}\t", oFeature.GetFieldAsDouble(iField));
break;
case FieldType.OFTInteger:
Console.WriteLine("{0}\t", oFeature.GetFieldAsInteger(iField));
break;
default:
Console.WriteLine("{0}\t", oFeature.GetFieldAsString(iField));
break;
}
}
Geometry oGeometry =oFeature.GetGeometryRef();
break;
}
Console.WriteLine( "数据处理完毕" );
Console.ReadKey(true);
}
}
}