Using GDAL in .NET Core

GDAL(https://gdal.org/, Geospatial Data Abstraction Library) is a frequently used geospatial library for manipulating geospatial data. The library is written in C++.

To use the GDAL library in .NET Core there are some NuGet packages available:

For Windows (on NuGet.org):

https://www.nuget.org/packages/Gdal.Core/2.3.0-beta-023
https://www.nuget.org/packages/Gdal.Core.WindowsRuntime/2.3.0-beta-023

For Linux (on  MyGet):

https://www.myget.org/feed/gdalcore/package/nuget/Gdal.Core (Gdal.Core 2.3.0-beta-024-1801)
https://www.myget.org/feed/gdalcore/package/nuget/Gdal.Core.LinuxRuntime (Gdal.Core.LinuxRuntime 2.3.0-beta-024-1840)

As we want to build are projects cross platform, we want to use the Windows NuGet packages when building on Windows, and use the Linux MyGet packages when building on Linux. How to do that?

First we need to add NuGet and MyGet to the ‘RestoreSources’ in the project file:

<RestoreSources>             $(RestoreSources);https://api.nuget.org/v3/index.json;https://www.myget.org/F/gdalcore/api/v3/index.json
</RestoreSources>

Second we need a conditional PackageReference depending on operating system:

<ItemGroup Condition="’$(OS)’ == ‘Unix’">
<PackageReference Include="Gdal.Core" Version="2.3.0-beta-024-1801" />
<PackageReference Include="Gdal.Core.LinuxRuntime" Version="2.3.0-beta-024-1840"/>
</ItemGroup>
<ItemGroup Condition="’$(OS)’ != ‘Unix’">
<PackageReference Include="Gdal.Core" Version="2.3.0-beta-023"/>
<PackageReference Include="Gdal.Core.WindowsRuntime" Version="2.3.0-beta-023"/>
</ItemGroup>

And now we can write code using GDAL functionality. For example load a GeoJSON file:

Gdal.AllRegister();
Ogr.RegisterAll();

var geojsonDriver = Ogr.GetDriverByName("GeoJSON");
var ds = geojsonDriver.Open(@"gemeenten2016.geojson", 0);
var layer1 = ds.GetLayerByName("gemeenten2016");
var features = layer1.GetFeatureCount(0);
Console.WriteLine("features in geojson: " + features);

Or we can do other GDAL stuff like coordinate transformations. This trick also works in Docker, just remember to install ‘gdal-bin’ and ‘libproj-dev’ on the system when on Linux. For a complete sample console application see https://github.com/bertt/GdalOnNetCoreSample

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s