//解决shp属性乱码问题
[DllImport("gdal204.dll", EntryPoint = "OGR_F_GetFieldAsString", CallingConvention = CallingConvention.Cdecl)]
public extern static System.IntPtr OGR_F_GetFieldAsString(HandleRef handle, int i);
/// <summary>
/// 解决中文乱码问题
/// </summary>
/// <param name="fe">当前要素</param>
/// <param name="index">字段</param>
/// <returns></returns>
public static string getRightStr(Feature fe, int index)
{
string str = string.Empty;
IntPtr pchar = OGR_F_GetFieldAsString(OSGeo.OGR.Feature.getCPtr(fe), index);
if (pchar == IntPtr.Zero)
return str;
byte[] unibytes = System.Text.Encoding.Unicode.GetBytes(Marshal.PtrToStringUni(pchar));//转成UNICODE编码
int length = 0;
for (int i = 0; i < unibytes.Length; i++)
{
if (unibytes[i] == 0)
{
break;
}
length++;
}
byte[] bytes = new byte[length];
Array.Copy(unibytes, bytes, length);
str = System.Text.Encoding.UTF8.GetString(bytes);//再转成UTF8
return str;
}
string strDataPath = @"C:\Users\Desktop\0807\新建文件地理数据库.gdb";
// 为了使用 GDAL,我们需要先注册所有的驱动
GdalConfiguration.ConfigureGdal();
GdalConfiguration.ConfigureOgr();
OSGeo.GDAL.Gdal.AllRegister();
OSGeo.OGR.Ogr.RegisterAll();
// 为了支持中文路径
//OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");//NO YES
//OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "UTF-8");//CP936
//Gdal.SetConfigOption("FILEGDB_ENCODING", "UTF-8");//UTF-8
// 为了使属性表字段支持中文
//OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "");
using (OSGeo.OGR.Driver driver = Ogr.GetDriverByName("OpenFileGDB"))//OpenFileGDB
using (DataSource dataSource = driver.Open(strDataPath, 0))
{
for (int i = 0; i < dataSource.GetLayerCount(); i++)
{
//获取图层
Layer layer = dataSource.GetLayerByIndex(i);
Debug.WriteLine($"{i} {layer.GetName()}");
do
{
//获取图层下的要素
Feature feature = layer.GetNextFeature();
if (null == feature)
{
break;
}
Debug.WriteLine(feature.GetStyleString());
//获取geometry
string strWkt = "";
feature.GetGeometryRef().ExportToWkt(out strWkt);
Debug.WriteLine(strWkt);//也可以ExportToWkb() gml等等
//获取属性
for (int p = 0; p < feature.GetFieldCount(); p++)
{
//Debug.WriteLine($"{feature.GetFieldDefnRef(p).GetName()}\t{feature.GetFieldAsString(p)}");
var v = feature.GetFieldAsString(p);
var str=getRightStr(feature, p);
}
feature.Dispose();
} while (true);
layer.Dispose();
}
}