private static void WriteShape(IGeometryCollection geometries, string shapepath)
 {
     if (File.Exists(shapepath))
         File.Delete(shapepath);
     var sfw = new ShapefileWriter(geometries.Factory);
     sfw.Write(Path.GetFileNameWithoutExtension(shapepath), geometries);
 }
        /// <summary>
        /// Writes the specified feature collection.
        /// </summary>
        /// <param name="featureCollection">The feature collection.</param>
        public void Write(IEnumerable <IFeature> featureCollection)
        {
            // Test if the Header is initialized
            if (Header is null)
            {
                throw new ApplicationException("Header must be set first!");
            }

            using (var featuresEnumerator = featureCollection.GetEnumerator())
            {
                // scan the original sequence looking for a geometry that we can
                // use to figure out the shape type.  keep the original features
                // around so we don't have to loop through the input twice; we
                // shouldn't have to look *too* far for a non-empty geometry.
                Geometry representativeGeometry = null;
                var      headFeatures           = new List <IFeature>();
                while (representativeGeometry?.IsEmpty != false && featuresEnumerator.MoveNext())
                {
                    var feature = featuresEnumerator.Current;
                    headFeatures.Add(feature);
                    representativeGeometry = feature.Geometry;
                }

                var shapeFileType = Shapefile.GetShapeType(representativeGeometry);
                using (_dbaseWriter)
                    using (var shapefileWriter = new ShapefileWriter(_geometryFactory, _streamProviderRegistry, shapeFileType))
                    {
                        _dbaseWriter.Write(Header);
                        string[] fieldNames = Array.ConvertAll(Header.Fields, field => field.Name);
                        object[] values     = new object[fieldNames.Length];

                        // first, write the one(s) that we scanned already.
                        foreach (var feature in headFeatures)
                        {
                            Write(feature);
                        }

                        // now continue through the features we haven't scanned yet.
                        while (featuresEnumerator.MoveNext())
                        {
                            Write(featuresEnumerator.Current);
                        }

                        void Write(IFeature feature)
                        {
                            shapefileWriter.Write(feature.Geometry);

                            var attribs = feature.Attributes;

                            for (int i = 0; i < fieldNames.Length; i++)
                            {
                                values[i] = attribs[fieldNames[i]];
                            }

                            _dbaseWriter.Write(values);
                        }
                    }
            }
        }
Example #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ShapefileDataWriter"/> class.
        /// </summary>
        /// <param name="fileName">File path without any extension</param>
        /// <param name="geometryFactory"></param>
        public ShapefileDataWriter(string fileName, IGeometryFactory geometryFactory)
        {
            this.geometryFactory = geometryFactory;

            // Files
            shpFile = fileName;
            dbfFile = fileName + ".dbf";

            // Writers
            shapeWriter = new ShapefileWriter(geometryFactory);
            dbaseWriter = new DbaseFileWriter(dbfFile);
        }
        /// <summary>
        /// Writes the specified feature collection.
        /// </summary>
        /// <param name="featureCollection">The feature collection.</param>
        public void Write(IList <IFeature> featureCollection)
        {
            // Test if the Header is initialized
            if (Header == null)
            {
                throw new ApplicationException("Header must be set first!");
            }

#if DEBUG
            // Test if all elements of the collections are features
            foreach (object obj in featureCollection)
            {
                if (obj.GetType().IsAssignableFrom(typeof(IFeature)))
                {
                    throw new ArgumentException("All the elements in the given collection must be " + typeof(IFeature).Name);
                }
            }
#endif

            try
            {
                // Write shp and shx
                var geometries = new IGeometry[featureCollection.Count];
                var index      = 0;
                foreach (IFeature feature in featureCollection)
                {
                    geometries[index++] = feature.Geometry;
                }
                ShapefileWriter.WriteGeometryCollection(_shpFile, new GeometryCollection(geometries, _geometryFactory));

                // Write dbf
                _dbaseWriter.Write(Header);
                foreach (IFeature feature in featureCollection)
                {
                    var       attribs = feature.Attributes;
                    ArrayList values  = new ArrayList();
                    for (int i = 0; i < Header.NumFields; i++)
                    {
                        values.Add(attribs[Header.Fields[i].Name]);
                    }
                    _dbaseWriter.Write(values);
                }
            }
            finally
            {
                // Close dbf writer
                _dbaseWriter.Close();
            }
        }
        public static void WriteGeometryCollection(ShapefileWriter shapefileWriter, DbaseFileWriter dbfWriter,
                                                   GeometryCollection geometryCollection, bool writeDummyDbf = true)
        {
            int numShapes = geometryCollection.NumGeometries;

            for (int i = 0; i < numShapes; i++)
            {
                shapefileWriter.Write(geometryCollection[i]);
            }

            if (writeDummyDbf)
            {
                WriteDummyDbf(dbfWriter, numShapes);
            }
        }
        public static void WriteGeometryCollection(IStreamProviderRegistry streamProviderRegistry,
                                                   GeometryCollection geometryCollection, bool createDummyDbf = true)
        {
            var shapeFileType = Shapefile.GetShapeType(geometryCollection);

            using (var writer = new ShapefileWriter(geometryCollection.Factory, streamProviderRegistry, shapeFileType))
            {
                var dbfWriter = createDummyDbf ? new DbaseFileWriter(streamProviderRegistry) : null;
                WriteGeometryCollection(writer, dbfWriter, geometryCollection, createDummyDbf);
                if (dbfWriter != null)
                {
                    dbfWriter.Dispose();
                }
            }
        }
Example #7
0
        /// <summary>
        /// Method to write a collection of geometries to a shapefile on disk.
        /// </summary>
        /// <remarks>
        /// Assumes the type given for the first geometry is the same for all subsequent geometries.
        /// For example, is, if the first Geometry is a Multi-polygon/ Polygon, the subsequent geometies are
        /// Muli-polygon/ polygon and not lines or points.
        /// The dbase file for the corresponding shapefile contains one column called row. It contains
        /// the row number.
        /// </remarks>
        /// <param name="filename">The filename to write to (minus the .shp extension).</param>
        /// <param name="geometryCollection">The GeometryCollection to write.</param>
        public static void WriteGeometryCollection(string filename, IGeometryCollection geometryCollection)
        {
            var shapeFileType = Shapefile.GetShapeType(geometryCollection);

            var numShapes = geometryCollection.NumGeometries;

            using (var writer = new ShapefileWriter(geometryCollection.Factory, filename, shapeFileType))
            {
                for (var i = 0; i < numShapes; i++)
                {
                    writer.Write(geometryCollection[i]);
                }
            }

            WriteDummyDbf(filename + ".dbf", numShapes);
        }
        /// <summary>
        /// Write the enumeration of features to shapefile (shp, shx and dbf)
        /// </summary>
        /// <param name="filename">Filename to create</param>
        /// <param name="features">Enumeration of features to write, features will be enumerated once</param>
        /// <param name="fields">Fields that should be written, only those attributes specified here will be mapped from the feature attributetable while writing</param>
        /// <param name="shapeGeometryType">Type of geometries shapefile</param>
        /// <param name="dbfEncoding">Optional Encoding to be used when writing the DBF-file (default Windows-1252)</param>
        public static void WriteFeatures(string filename, IEnumerable <IFeature> features, DbaseFieldDescriptor[] fields, ShapeGeometryType shapeGeometryType,
                                         Encoding dbfEncoding = null)
        {
            // Set default encoding if not specified
            if (dbfEncoding == null)
            {
                dbfEncoding = DbaseEncodingUtility.GetEncodingForCodePageIdentifier(1252);
            }

            // Open shapefile and dbase stream writers
            using (var shpWriter = new ShapefileWriter(Path.ChangeExtension(filename, ".shp"), shapeGeometryType))
            {
                using (var dbfWriter = new DbaseFileWriter(Path.ChangeExtension(filename, ".dbf"), dbfEncoding))
                {
                    var dbfHeader = new DbaseFileHeader(dbfEncoding);
                    foreach (var field in fields)
                    {
                        dbfHeader.AddColumn(field.Name, field.DbaseType, field.Length, field.DecimalCount);
                    }
                    dbfWriter.Write(dbfHeader);

                    int      numFeatures = 0;
                    string[] fieldNames  = Array.ConvertAll(fields, field => field.Name);
                    object[] values      = new object[fieldNames.Length];
                    foreach (var feature in features)
                    {
                        shpWriter.Write(feature.Geometry);
                        for (int i = 0; i < fieldNames.Length; i++)
                        {
                            values[i] = feature.Attributes[fieldNames[i]];
                        }
                        dbfWriter.Write(values);
                        numFeatures++;
                    }

                    // set the number of records
                    dbfHeader.NumRecords = numFeatures;
                    // Update the header
                    dbfWriter.Write(dbfHeader);
                    // write the end of dbase file marker
                    dbfWriter.WriteEndOfDbf();
                    // close the dbase stream
                    dbfWriter.Close();
                }
            }
        }
		/// <summary>
		/// Method to write a collection of geometries to a shapefile on disk.
		/// </summary>
		/// <remarks>
		/// Assumes the type given for the first geometry is the same for all subsequent geometries.
		/// For example, is, if the first Geometry is a Multi-polygon/ Polygon, the subsequent geometies are
		/// Muli-polygon/ polygon and not lines or points.
		/// The dbase file for the corresponding shapefile contains one column called row. It contains 
		/// the row number.
		/// </remarks>
		/// <param name="filename">The filename to write to (minus the .shp extension).</param>
		/// <param name="geometryCollection">The GeometryCollection to write.</param>		
		public static void WriteGeometryCollection(string filename, IGeometryCollection geometryCollection)
		{
		    var shapeFileType = Shapefile.GetShapeType(geometryCollection);

		    var numShapes = geometryCollection.NumGeometries;
            using (var writer = new ShapefileWriter(geometryCollection.Factory, filename, shapeFileType))
		    {
		        for (var i = 0; i < numShapes; i++)
		        {
		            writer.Write(geometryCollection[i]);
		        }
		    }

            WriteDummyDbf(filename + ".dbf", numShapes);

		}
        /// <summary>
        /// Write the enumeration of features to shapefile (shp, shx and dbf)
        /// </summary>
        /// <param name="filename">Filename to create</param>
        /// <param name="features">Enumeration of features to write, features will be enumerated once</param>
        /// <param name="fields">Fields that should be written, only those attributes specified here will be mapped from the feature attributetable while writing</param>
        /// <param name="shapeGeometryType">Type of geometries shapefile</param>
        /// <param name="dbfEncoding">Optional Encoding to be used when writing the DBF-file (default Windows-1252)</param>
        public static void WriteFeatures(string filename, IEnumerable<IFeature> features, DbaseFieldDescriptor[] fields, ShapeGeometryType shapeGeometryType,
            Encoding dbfEncoding = null)
        {

            // Set default encoding if not specified
            if (dbfEncoding == null)
                dbfEncoding = Encoding.GetEncoding(1252);

            // Open shapefile and dbase stream writers
            using (var shpWriter = new ShapefileWriter(Path.ChangeExtension(filename, ".shp"), shapeGeometryType))
            {
                using (var dbfWriter = new DbaseFileWriter(Path.ChangeExtension(filename, ".dbf"), dbfEncoding))
                {
                    var dbfHeader = new DbaseFileHeader(dbfEncoding);
                    foreach (var field in fields)
                    {
                        dbfHeader.AddColumn(field.Name, field.DbaseType, field.Length, field.DecimalCount);
                    }
                    dbfWriter.Write(dbfHeader);

                    var numFeatures = 0;
                    foreach (var feature in features)
                    {
                        shpWriter.Write(feature.Geometry);
                        var values = new object[fields.Length];
                        for (var i = 0; i < fields.Length; i++)
                        {
                            values[i] = feature.Attributes[fields[i].Name];
                        }
                        dbfWriter.Write(values);
                        numFeatures++;
                    }

                    // set the number of records
                    dbfHeader.NumRecords = numFeatures;
                    // Update the header
                    dbfWriter.Write(dbfHeader);
                    // write the end of dbase file marker
                    dbfWriter.WriteEndOfDbf();
                    // close the dbase stream
                    dbfWriter.Close();
                }
            }
        }
        public static void WriteGeometryCollection(ShapefileWriter shapefileWriter, DbaseFileWriter dbfWriter,
            IGeometryCollection geometryCollection, bool writeDummyDbf = true)
        {
            var numShapes = geometryCollection.NumGeometries;
            for (var i = 0; i < numShapes; i++)
            {
                shapefileWriter.Write(geometryCollection[i]);
            }

            if (writeDummyDbf)
            {
                WriteDummyDbf(dbfWriter, numShapes);
            }

        }
 public static void WriteGeometryCollection(IStreamProviderRegistry streamProviderRegistry,
     IGeometryCollection geometryCollection, bool createDummyDbf = true)
 {
     var shapeFileType = Shapefile.GetShapeType(geometryCollection);
     using (var writer = new ShapefileWriter(geometryCollection.Factory, streamProviderRegistry, shapeFileType))
     {
         var dbfWriter = createDummyDbf ? new DbaseFileWriter(streamProviderRegistry) : null;
         WriteGeometryCollection(writer, dbfWriter, geometryCollection, createDummyDbf);
         if (dbfWriter != null)
             dbfWriter.Dispose();
     }
 }
        public void TestReadingShapeFileAfvalbakken()
        {
            IGeometryFactory factory = GeometryFactory.Default;
            List<IPolygon> polys = new List<IPolygon>();
            const int distance = 500;
            using (ShapefileDataReader reader = new ShapefileDataReader("afvalbakken", factory))
            {
                int index = 0;
                while (reader.Read())
                {                    
                    IGeometry geom = reader.Geometry;
                    Assert.IsNotNull(geom);
                    Assert.IsTrue(geom.IsValid);
                    Debug.WriteLine(String.Format("Geom {0}: {1}", index++, geom));
                    
                    IGeometry buff = geom.Buffer(distance);
                    Assert.IsNotNull(buff);

                    polys.Add((IPolygon) geom);
                }
            }

            IMultiPolygon multiPolygon = factory.CreateMultiPolygon(polys.ToArray());
            Assert.IsNotNull(multiPolygon);
            Assert.IsTrue(multiPolygon.IsValid);

            IMultiPolygon multiBuffer = (IMultiPolygon) multiPolygon.Buffer(distance);
            Assert.IsNotNull(multiBuffer);            
            Assert.IsTrue(multiBuffer.IsValid);

            ShapefileWriter writer = new ShapefileWriter(factory); 
            writer.Write(@"test_buffer", multiBuffer); 
            ShapefileWriter.WriteDummyDbf(@"test_buffer.dbf", multiBuffer.NumGeometries);        
        }
        public static void WriteGeometryCollection(ShapefileWriter shapefileWriter, DbaseFileWriter dbfWriter, IGeometryCollection geometryCollection)
        {
            var shapeFileType = Shapefile.GetShapeType(geometryCollection);

            var numShapes = geometryCollection.NumGeometries;

            for (var i = 0; i < numShapes; i++)
            {
                shapefileWriter.Write(geometryCollection[i]);
            }


            WriteDummyDbf(dbfWriter, numShapes);

        }
        public static void WriteGeometryCollection(IStreamProviderRegistry streamProviderRegistry, IGeometryCollection geometryCollection)
        {
            var shapeFileType = Shapefile.GetShapeType(geometryCollection);

            var numShapes = geometryCollection.NumGeometries;
            using (var writer = new ShapefileWriter(geometryCollection.Factory, streamProviderRegistry, shapeFileType))
            {
                for (var i = 0; i < numShapes; i++)
                {
                    writer.Write(geometryCollection[i]);
                }
            }

            WriteDummyDbf(streamProviderRegistry, numShapes);

        }
Example #16
0
        private void TestBugCimino()
        {
            try
            {
                string file = "countryCopy.shp";
                if (!File.Exists(file))
                    throw new FileNotFoundException();

                ShapefileReader sfr = new ShapefileReader(file);

                IGeometryCollection gc = sfr.ReadAll();
                for (int i = 0; i < gc.NumGeometries; i++)
                    Console.WriteLine(i + " " + gc.Geometries[i].Envelope);
           
                // IsValidOp.CheckShellsNotNested molto lento nell'analisi di J == 7 (Poligono con 11600 punti)
                var write = Path.Combine(Path.GetTempPath(), "copy_countryCopy");
                var sfw = new ShapefileWriter(gc.Factory);
                sfw.Write(write, gc);
                Console.WriteLine("Write Complete!");
            }
            catch (Exception ex) 
            {                
                throw ex;
            }
        }