public ShapefileWriter(GeometryFactory geometryFactory, IStreamProviderRegistry streamProviderRegistry,
                               ShapeGeometryType geomType)
            : this(geometryFactory)
        {
            _shpStream = streamProviderRegistry[StreamTypes.Shape].OpenWrite(true);
            _shxStream = streamProviderRegistry[StreamTypes.Index]?.OpenWrite(true);

            _geometryType = geomType;

            _shpBinaryWriter = new BigEndianBinaryWriter(_shpStream);

            WriteShpHeader(_shpBinaryWriter, 0, new Envelope(0, 0, 0, 0));
            if (_shxStream != null)
            {
                _shxBinaryWriter = new BigEndianBinaryWriter(_shxStream);
                WriteShxHeader(_shxBinaryWriter, 0, new Envelope(0, 0, 0, 0));
            }

            _shapeHandler = Shapefile.GetShapeHandler(geomType);
        }
            /// <summary>
            /// Initializes a new instance of the <see cref="ShapefileEnumerator"/> class.
            /// </summary>
            /// <param name="shapefile"></param>
            public ShapefileEnumerator(ShapeMemoryStreamReader shapefile)
            {
                _parent = shapefile;

                // create a file stream for each enumerator that is given out. This allows the same file
                // to have one or more enumerator. If we used the parents stream - than only one IEnumerator
                // could be given out.
                //var stream = new FileStream(_parent._inputStream, FileMode.Open, FileAccess.Read, FileShare.Read);
                _shpBinaryReader = new BigEndianBinaryReader(_parent._inputStream);

                // skip header - since parent has already read this.
                _shpBinaryReader.ReadBytes(100);
                ShapeGeometryType type = _parent._mainHeader.ShapeType;

                _handler = Shapefile.GetShapeHandler(type);
                if (_handler == null)
                {
                    throw new NotSupportedException("Unsuported shape type:" + type);
                }
            }
예제 #3
0
            /// <summary>
            ///     Initializes a new instance of the <see cref="ShapefileEnumerator" /> class.
            /// </summary>
            /// <param name="shapefile"></param>
            public ShapefileEnumerator(ShapefileReader shapefile)
            {
                _parent = shapefile;

                // create a file stream for each enumerator that is given out. This allows the same file
                // to have one or more enumerator. If we used the parents stream - than only one IEnumerator
                // could be given out.
                var stream = shapefile._shapeStreamProviderRegistry[StreamTypes.Shape].OpenRead();

                _shpBinaryReader = new BigEndianBinaryReader(stream);

                // skip header - since parent has already read this.
                _shpBinaryReader.ReadBytes(100);
                var type = _parent._mainHeader.ShapeType;

                _handler = Shapefile.GetShapeHandler(type);
                if (_handler == null)
                {
                    throw new NotSupportedException("Unsuported shape type:" + type);
                }
            }
예제 #4
0
        /// <summary>
        /// Reads the shapefile and returns a GeometryCollection representing all the records in the shapefile.
        /// </summary>
        /// <returns>GeometryCollection representing every record in the shapefile.</returns>
        public IGeometryCollection ReadAll()
        {
            var list = new List <IGeometry>();
            ShapeGeometryType type    = _mainHeader.ShapeType;
            ShapeHandler      handler = Shapefile.GetShapeHandler(type);

            if (handler == null)
            {
                throw new NotSupportedException("Unsupported shape type:" + type);
            }

            int i = 0;

            foreach (IGeometry geometry in this)
            {
                list.Add(geometry);
                i++;
            }

            IGeometry[] geomArray = GeometryFactory.ToGeometryArray(list);
            return(_geometryFactory.CreateGeometryCollection(geomArray));
        }
예제 #5
0
        public ShapefileWriter(IGeometryFactory geometryFactory, string filename, ShapeGeometryType geomType)
            : this(geometryFactory)
        {
            var folder = Path.GetDirectoryName(filename) ?? ".";
            var file   = Path.GetFileNameWithoutExtension(filename);
            if (string.IsNullOrEmpty(file))
            {
                throw new ArgumentException(string.Format("Filename '{0}' is not valid", filename), "filename");
            }
            filename = Path.Combine(folder, file);

            _shpStream = new FileStream(filename + ".shp", FileMode.Create);
            _shxStream = new FileStream(filename + ".shx", FileMode.Create);

            _geometryType = geomType;

            _shpBinaryWriter = new BigEndianBinaryWriter(_shpStream);
            _shxBinaryWriter = new BigEndianBinaryWriter(_shxStream);

            WriteShpHeader(_shpBinaryWriter, 0, new Envelope(0, 0, 0, 0), geomType);
            WriteShxHeader(_shxBinaryWriter, 0, new Envelope(0, 0, 0, 0), geomType);

            _shapeHandler = Shapefile.GetShapeHandler(geomType);
        }
        /// <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 == null)
            {
                throw new ApplicationException("Header must be set first!");
            }

#if DEBUG
            // Test if all elements of the collections are features
            featureCollection = new List <IFeature>(featureCollection);
            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, nameof(featureCollection));
                }
            }
#endif

            using (IEnumerator <IFeature> 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.
                IGeometry       representativeGeometry = null;
                List <IFeature> headFeatures           = new List <IFeature>();
                while (representativeGeometry?.IsEmpty != false && featuresEnumerator.MoveNext())
                {
                    IFeature 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);
                        var fieldNames = Array.ConvertAll(Header.Fields, field => field.Name);
                        var values     = new object[fieldNames.Length];

                        // first, write the one(s) that we scanned already.
                        foreach (IFeature 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);
                        }
                    }
            }
        }
예제 #7
0
        /// <summary>
        /// Writes a shapefile to 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 void Write(IGeometryCollection geometryCollection)
        {
            //FileStream shpStream = new FileStream(filename + ".shp", FileMode.Create);
            //FileStream shxStream = new FileStream(filename + ".shx", FileMode.Create);

            shpStream = new MemoryStream();
            shxStream = new MemoryStream();
            BigEndianBinaryWriter shpBinaryWriter = new BigEndianBinaryWriter(shpStream);
            BigEndianBinaryWriter shxBinaryWriter = new BigEndianBinaryWriter(shxStream);

            // assumes
            ShapeHandler handler = Shapefile.GetShapeHandler(Shapefile.GetShapeType(geometryCollection.Geometries[0]));

            IGeometry body;
            int       numShapes = geometryCollection.NumGeometries;
            // calc the length of the shp file, so it can put in the header.
            int shpLength = 50;

            for (int i = 0; i < numShapes; i++)
            {
                body       = (IGeometry)geometryCollection.Geometries[i];
                shpLength += 4;                       // length of header in WORDS
                shpLength += handler.GetLength(body); // length of shape in WORDS
            }

            int shxLength = 50 + (4 * numShapes);

            // write the .shp header
            ShapefileHeader shpHeader = new ShapefileHeader();

            shpHeader.FileLength = shpLength;

            // get envelope in external coordinates
            Envelope env    = geometryCollection.EnvelopeInternal as Envelope;
            Envelope bounds = ShapeHandler.GetEnvelopeExternal(geometryFactory.PrecisionModel, env);

            shpHeader.Bounds = bounds;

            // assumes Geometry type of the first item will the same for all other items
            // in the collection.
            shpHeader.ShapeType = Shapefile.GetShapeType(geometryCollection.Geometries[0]);
            shpHeader.Write(shpBinaryWriter);

            // write the .shx header
            ShapefileHeader shxHeader = new ShapefileHeader();

            shxHeader.FileLength = shxLength;
            shxHeader.Bounds     = shpHeader.Bounds;

            // assumes Geometry type of the first item will the same for all other items in the collection.
            shxHeader.ShapeType = Shapefile.GetShapeType(geometryCollection.Geometries[0]);
            shxHeader.Write(shxBinaryWriter);

            // write the individual records.
            int _pos = 50; // header length in WORDS

            for (int i = 0; i < numShapes; i++)
            {
                body = geometryCollection.Geometries[i];
                int recordLength = handler.GetLength(body);
                shpBinaryWriter.WriteIntBE(i + 1);
                shpBinaryWriter.WriteIntBE(recordLength);

                shxBinaryWriter.WriteIntBE(_pos);
                shxBinaryWriter.WriteIntBE(recordLength);

                _pos += 4;            // length of header in WORDS
                handler.Write(body, shpBinaryWriter, geometryFactory);
                _pos += recordLength; // length of shape in WORDS
            }

            shxBinaryWriter.Flush();
            //shxStream.Seek(0, SeekOrigin.Begin);
            ////shxBinaryWriter.Close();
            shpBinaryWriter.Flush();
            //shpStream.Seek(0, SeekOrigin.Begin);
            //shpBinaryWriter.Close();

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