0

I am currently coding a C#/WPF application that lets you choose two shapefiles and create a new merged one, with the content of both shapefiles.

My problem is that I am quite new (1 month with gis) and I need to use C# libraries whilst they are a little different from the Python ones.

I am trying to imitate the behaviour of the python example:

import os, ogr, osr

outputMergefn = 'merge.shp'
directory = "/Users/UserName/Downloads/"
fileStartsWith = 'test'
fileEndsWith = '.shp'
driverName = 'ESRI Shapefile'
geometryType = ogr.wkbPolygon

out_driver = ogr.GetDriverByName( driverName )
if os.path.exists(outputMergefn):
    out_driver.DeleteDataSource(outputMergefn)
out_ds = out_driver.CreateDataSource(outputMergefn)
out_layer = out_ds.CreateLayer(outputMergefn, geom_type=geometryType)

fileList = os.listdir(directory)

for file in fileList:
    if file.startswith(fileStartsWith) and file.endswith(fileEndsWith):
        print file
        ds = ogr.Open(directory+file)
        lyr = ds.GetLayer()
        for feat in lyr:
            out_feat = ogr.Feature(out_layer.GetLayerDefn())
            out_feat.SetGeometry(feat.GetGeometryRef().Clone())
            out_layer.CreateFeature(out_feat)
            out_feat = None
            out_layer.SyncToDisk()

In this example, the program takes each feature of each shapefile, cloning the geometry elements into new features that are attached to the new layer.

private void JoinShapefile(String path, Layer out_layer){
        DataSource ds = driver.Open(path, 0);
        Layer in_layer = ds.GetLayerByIndex(0);

        for (long i = 0; i < in_layer.GetFeatureCount(0); i++)
        {
            Feature in_feat = in_layer.GetFeature(i);
            Feature out_feat = new OSGeo.OGR.Feature(out_layer.GetLayerDefn());

            out_feat.SetGeometry(in_feat.GetGeometryRef().Clone());
            out_layer.CreateFeature(out_feat);

            out_feat = null;
            out_layer.SyncToDisk();

        }

    }

The function that I made takes a shapefile's path and "copies" its layer into the given out_layer. The goal of this method is to merge two shapefiles into a new one, by calling to this method twice, using two different shapefiles and one out_layer. The problem is that this code is just copying the geometry field of each feature.

How could I add also the rest of fields and data per each feature?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.