adminsystem/adminsystem.Utils/commonutils/ShapeUtils.cs

43 lines
1.2 KiB
C#

using OSGeo.GDAL;
using OSGeo.OGR;
namespace adminsystem.Utils.commonutils;
/// <summary>
/// shapefile操作类
/// </summary>
public class ShapeUtils
{
public ShapeUtils()
{
//加载驱动,设置中文
Gdal.AllRegister();
Ogr.RegisterAll();
Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");
Gdal.SetConfigOption("SHAPE_ENCODING", "");
}
public static void Shape2Json(string filepath)
{
DataSource ds = Ogr.Open(filepath,1);
if (ds == null)
{
throw new Exception($"Failed to open file: {filepath}");
}
Layer layer = ds.GetLayerByIndex(0);
if (layer == null)
{
throw new Exception("Layer not found in SHP file.");
}
var geoJsonPath = Path.ChangeExtension(filepath, "geojson");
var geoJsonDs = Ogr.GetDriverByName("GeoJSON").CreateDataSource(geoJsonPath, null);
if (geoJsonDs == null)
{
throw new Exception("Failed to create GeoJSON data source.");
}
geoJsonDs.CopyLayer(layer, layer.GetName(), null);
geoJsonDs.Dispose();
ds.Dispose();
layer.Dispose();
}
}