Hi I want to convert a shapefile (shp) to kml using Gdal library in C#. I write a code but the output is not in kml format.
Here is my code:
using OSGeo.OGR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OSGeo.OSR;
using OSGeo.GDAL;
namespace ConsoleApp1 {
class Program {
static void Main(string[] args) {
GdalConfiguration.ConfigureGdal();
GdalConfiguration.ConfigureOgr();
convert();
}
public static void convert() {
string shapeFilePath = @ "C:\riv1.shp";
Ogr.RegisterAll();
var drv = Ogr.GetDriverByName("ESRI Shapefile");
var ds = drv.Open(shapeFilePath, 0);
OSGeo.OGR.Layer layer = ds.GetLayerByIndex(0);
OSGeo.OGR.Feature f;
layer.ResetReading();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
while ((f = layer.GetNextFeature()) != null) {
var geom = f.GetGeometryRef();
if (geom != null) {
var geometryKml = geom.ExportToKML("");
sb.AppendLine(geometryKml);
}
}
var kmlStr = sb.ToString();
System.IO.File.WriteAllText("c:/riv1.kml", kmlStr);
}
}
}
This convert work fine by FWTools Shell but I need to do it in my code. Please help me if you know what I miss.
You can use the CopyLayer() method to just copy the shapefile layer to a new Kml datasource.