Skip to content

Instantly share code, notes, and snippets.

@osya
Last active March 1, 2023 19:40
Show Gist options
  • Save osya/251ee7c5d1e696d5f2aa to your computer and use it in GitHub Desktop.
Save osya/251ee7c5d1e696d5f2aa to your computer and use it in GitHub Desktop.
Using the NetTopologySuite (NTS) to read and write Shapefiles in C# #CSharp
using GisSharpBlog.NetTopologySuite.Features;
using GisSharpBlog.NetTopologySuite.Geometries;
using GisSharpBlog.NetTopologySuite.IO;
using GeoAPI.Geometries;
...etc....
GeometryFactory factory = new GeometryFactory();
ShapefileDataReader shapeFileDataReader = new ShapefileDataReader(shpFilename, factory);
//Display the shapefile type
ShapefileHeader shpHeader = shapeFileDataReader.ShapeHeader;
Console.WriteLine(string.Format("Shape type: {0}", shpHeader.ShapeType));
//Display the min and max bounds of the shapefile
IEnvelope bounds = shpHeader.Bounds;
Console.WriteLine(string.Format("Min bounds: ({0},{1})", bounds.MinX, bounds.MinY));
Console.WriteLine(string.Format("Max bounds: ({0},{1})", bounds.MaxX, bounds.MaxY));
//Display summary information about the Dbase file
DbaseFileHeader header = shapeFileDataReader.DbaseHeader;
Console.WriteLine("Dbase info");
Console.WriteLine(string.Format("{0} Columns, {1} Records", header.Fields.Length, header.NumRecords));
for (int i = 0; i < header.NumFields; i++)
{
DbaseFieldDescriptor fldDescriptor = header.Fields[i];
Console.WriteLine(string.Format(" {0} {1}", fldDescriptor.Name, fldDescriptor.DbaseType));
}
//Reset the pointer to the start of the shapefile, just in case
//shapeFileDataReader.Reset();
//Read through all records of the shapefile (geometry and attributes) into a feature collection
ArrayList features = new ArrayList();
while (shapeFileDataReader.Read())
{
Feature feature = new Feature();
AttributesTable attributesTable = new AttributesTable();
string[] keys = new string[header.NumFields];
IGeometry geometry = (Geometry)shapeFileDataReader.Geometry;
for (int i = 0; i < header.NumFields; i++)
{
DbaseFieldDescriptor fldDescriptor = header.Fields[i];
keys[i] = fldDescriptor.Name;
attributesTable.AddAttribute(fldDescriptor.Name, shapeFileDataReader.GetValue(i));
}
feature.Geometry = geometry;
feature.Attributes = attributesTable;
features.Add(feature);
}
//Close and free up any resources
shapeFileDataReader.Close();
shapeFileDataReader.Dispose();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment