Ejemplo n.º 1
0
        public ShapeReader(IStreamProviderRegistry streamProviderRegistry)
        {
            if (streamProviderRegistry == null)
                throw new ArgumentNullException("streamProviderRegistry");

            m_StreamProviderRegistry = streamProviderRegistry;

            m_ShapeFileHeader = new ShapefileHeader(ShapeReaderStream);
            m_ShapeHandler = Shapefile.GetShapeHandler(ShapefileHeader.ShapeType);

            m_ShapeOffsetCache = new Lazy<long[]>(BuildOffsetCache, LazyThreadSafetyMode.ExecutionAndPublication);

        }
Ejemplo n.º 2
0
        /// <summary>
        /// This tests the specified file in order to determine what type of vector the file contains.
        /// This returns unspecified if the file format is not supported by this provider.
        /// </summary>
        /// <param name="fileName">The string fileName to test</param>
        /// <returns>A FeatureType clarifying what sort of features are stored on the data type.</returns>
        public virtual FeatureType GetFeatureType(string fileName)
        {
            ShapefileHeader sh = new ShapefileHeader(fileName);

            if (sh.ShapeType == ShapeType.Polygon || sh.ShapeType == ShapeType.PolygonM || sh.ShapeType == ShapeType.PolygonZ)
            {
                return(FeatureType.Polygon);
            }
            if (sh.ShapeType == ShapeType.PolyLine || sh.ShapeType == ShapeType.PolyLineM || sh.ShapeType == ShapeType.PolyLineZ)
            {
                return(FeatureType.Line);
            }
            if (sh.ShapeType == ShapeType.Point || sh.ShapeType == ShapeType.PointM || sh.ShapeType == ShapeType.PointZ)
            {
                return(FeatureType.Point);
            }
            if (sh.ShapeType == ShapeType.MultiPoint || sh.ShapeType == ShapeType.MultiPointM || sh.ShapeType == ShapeType.MultiPointZ)
            {
                return(FeatureType.MultiPoint);
            }
            return(FeatureType.Unspecified);
        }
Ejemplo n.º 3
0
        public static void Convert(ShapefileGeometryType type, SqlDataReader reader, string shapefile)
        {
            if (!reader.Read())
            {
                throw new Exception("No Results found");
            }

            int             geomOrdinal, colCount;
            ShapefileHeader shapeHeader = ShapefileHeader.CreateEmpty(type);
            DbfHeader       dbfHeader   = BuildHeader(reader, out geomOrdinal, out colCount);
            GeometryFactory factory     = new GeometryFactory();
            Envelope        env         = shapeHeader.Bounds;

            using (ShapefileDataWriter writer = ShapefileDataWriter.Create(shapefile, dbfHeader, shapeHeader))
            {
                do
                {
                    SqlGeometry geom = reader[geomOrdinal] as SqlGeometry;
                    if (!geom.STIsValid())
                    {
                        geom = geom.MakeValid();
                    }

                    for (int i = 0, offset = 0; i < colCount; i++)
                    {
                        if (i == geomOrdinal)
                        {
                            offset++;
                        }

                        writer.Record.SetRaw(i, reader[i + offset]);
                    }

                    ExpandEnv(env, geom.STBoundary());
                    writer.Write(ConvertToGeometry.SqlGeometryToGeometry(geom, factory));
                }while (reader.Read());
            }
        }
Ejemplo n.º 4
0
        public ShapeReader(string shapeFilePath)
        {
            if (shapeFilePath == null)
            {
                throw new ArgumentNullException("shapeFilePath");
            }

            if (string.IsNullOrWhiteSpace(shapeFilePath))
            {
                throw new ArgumentException("shapeFilePath", "Path to shapefile can't be empty");
            }

            if (!File.Exists(shapeFilePath))
            {
                throw new FileNotFoundException("Given shapefile doesn't exist", shapeFilePath);
            }

            m_ShapeFilePath = shapeFilePath;

            m_ShapeFileHeader = new ShapefileHeader(ShapeReaderStream);
            m_ShapeHandler    = Shapefile.GetShapeHandler(ShapefileHeader.ShapeType);

            m_ShapeOffsetCache = new Lazy <long[]>(BuildOffsetCache, LazyThreadSafetyMode.ExecutionAndPublication);
        }
Ejemplo n.º 5
0
	    public ShapeReader(string shapeFilePath)
		{
			if (shapeFilePath == null)
			{
				throw new ArgumentNullException("shapeFilePath");
			}

			if (string.IsNullOrWhiteSpace(shapeFilePath))
			{
				throw new ArgumentException("shapeFilePath", "Path to shapefile can't be empty");
			}

			if (!File.Exists(shapeFilePath))
			{
				throw new FileNotFoundException("Given shapefile doesn't exist", shapeFilePath);
			}

			m_ShapeFilePath = shapeFilePath;

			m_ShapeFileHeader = new ShapefileHeader(ShapeReaderStream);
			m_ShapeHandler = Shapefile.GetShapeHandler(ShapefileHeader.ShapeType);

			m_ShapeOffsetCache = new Lazy<long[]>(BuildOffsetCache, LazyThreadSafetyMode.ExecutionAndPublication);
		}
        public static void Reproject(string destinationFolder, string projection, params ReprojectShapefile[] shapes)
        {
            ProjectionInfo targetProjection = ProjectionInfo.FromEsriString(projection);

            foreach (ReprojectShapefile shape in shapes)
            {
                string shapePath = Path.Combine(destinationFolder, shape.DestinationName);

                ShapefileHeader shapeHeader = ShapefileHeader.CreateEmpty(ShapefileGeometryType.Polygon);
                DbfHeader       dbfHeader   = new DbfHeader();
                dbfHeader.AddCharacter("Label", 80);
                GeometryFactory gf = new GeometryFactory();

                using (ShapefileDataWriter writer = ShapefileDataWriter.Create(shapePath + ".shp", dbfHeader, shapeHeader))
                {
                    GeometryTransform transform = null;
                    if (File.Exists(Path.ChangeExtension(shape.Source, ".prj")))
                    {
                        transform = GeometryTransform.GetTransform(shape.Source, projection);

                        if (transform != null)
                        {
                            File.WriteAllText(shapePath + ".prj", projection);
                        }
                        else
                        {
                            File.Copy(Path.ChangeExtension(shape.Source, ".prj"), shapePath + ".prj");
                        }
                    }

                    using (ShapefileIndexReader index = new ShapefileIndexReader(Path.ChangeExtension(shape.Source, ".shx")))
                    {
                        if (transform != null)
                        {
                            writer.Header.Bounds.ExpandToInclude(transform.Apply(index.Header.Bounds));
                        }
                        else
                        {
                            writer.Header.Bounds.ExpandToInclude(index.Header.Bounds);
                        }

                        Task[] tasks = new Task[Environment.ProcessorCount];
                        for (int i = 0; i < tasks.Length; i++)
                        {
                            tasks[i] = Task.Factory.StartNew(() =>
                            {
                                using (ShapefileBlockReader reader = new ShapefileBlockReader(shape.Source, index, gf, transform))
                                {
                                    while (reader.Read())
                                    {
                                        writer.Write(reader.Geometry, reader.Record.GetString(shape.Label));
                                    }
                                }
                            });
                        }

                        Task.WaitAll(tasks);

                        writer.Flush();
                    }
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Writes an entire shapefile to disk in one call using a geometryCollection.
        /// </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 virtual void Write(string filename, GeometryCollection geometryCollection)
        {
            System.IO.FileStream shpStream = new System.IO.FileStream(filename + ".shp", System.IO.FileMode.Create);
            System.IO.FileStream shxStream = new System.IO.FileStream(filename + ".shx", System.IO.FileMode.Create);
            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 = 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 ShapeHeader = new ShapefileHeader();
            ShapeHeader.FileLength = shpLength;

            // get envelope in external coordinates
            IEnvelope env = geometryCollection.EnvelopeInternal;
            IEnvelope bounds = ShapeHandler.GetEnvelopeExternal(new PrecisionModel(geometryFactory.PrecisionModel), env);
            ShapeHeader.Bounds = bounds;

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

            // write the .shx header
            ShapefileHeader shxHeader = new ShapefileHeader();
            shxHeader.FileLength = shxLength;
            shxHeader.Bounds = ShapeHeader.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();
            shxBinaryWriter.Close();
            shpBinaryWriter.Flush();
            shpBinaryWriter.Close();

            // WriteDummyDbf(filename + ".dbf", numShapes);	
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Writes the geometry information from the specified IFeatureLayer to the file
        /// </summary>
        /// <param name="filename">A filename</param>
        /// <param name="Layer">An IFeatureLayer to save</param>
        public virtual void Write(string filename, IFeatureSet Layer)
        {
            if (Layer == null) return;
            if (Layer.Features == null) return;
            if (Layer.Features.Count == 0) return;
            string rootname, shpFile, shxFile;
            
            rootname = System.IO.Path.GetDirectoryName(filename) + "\\" + System.IO.Path.GetFileNameWithoutExtension(filename);
            shpFile = rootname + ".shp";
            shxFile = rootname + ".shx";
            
            System.IO.FileStream shpStream = new System.IO.FileStream(shpFile, System.IO.FileMode.Create);
            System.IO.FileStream shxStream = new System.IO.FileStream(shxFile, System.IO.FileMode.Create);
            BigEndianBinaryWriter shpBinaryWriter = new BigEndianBinaryWriter(shpStream);
            BigEndianBinaryWriter shxBinaryWriter = new BigEndianBinaryWriter(shxStream);

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

            ShapeHandler handler = null;

            switch (Layer.Features[0].FeatureType)
            {
                case FeatureTypes.Unspecified: return;
                case FeatureTypes.Line: handler = new MultiLineHandler();
                    break;
                case FeatureTypes.Point: handler = new PointHandler();
                    break;
                case FeatureTypes.Polygon: handler = new PolygonHandler();
                    break;
            }

            IBasicGeometry body;
            int numShapes = Layer.Features.Count;
            // 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 = Layer.Features[i].BasicGeometry;
                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 ShapeHeader = new ShapefileHeader();
            ShapeHeader.FileLength = shpLength;

            // get envelope in external coordinates
            IEnvelope env = Layer.Envelope;
            //IEnvelope bounds = ShapeHandler.GetEnvelopeExternal(new PrecisionModel(geometryFactory.PrecisionModel), env);
            ShapeHeader.Bounds = env;

            // write the .shx header
            ShapefileHeader shxHeader = new ShapefileHeader();
            shxHeader.FileLength = shxLength;
            shxHeader.Bounds = ShapeHeader.Bounds;

            // assumes Geometry type of the first item will the same for all other items
            // in the collection.
            switch(Layer.FeatureType)
            {
                case FeatureTypes.Polygon:
                    ShapeHeader.ShapeType = ShapeGeometryTypes.Polygon;
                    shxHeader.ShapeType = ShapeGeometryTypes.Polygon;
                    break;
                case FeatureTypes.Point:
                    ShapeHeader.ShapeType = ShapeGeometryTypes.Point;
                    shxHeader.ShapeType = ShapeGeometryTypes.Point;
                    break;
                case FeatureTypes.Line:
                    ShapeHeader.ShapeType = ShapeGeometryTypes.LineString;
                    shxHeader.ShapeType = ShapeGeometryTypes.LineString;
                    break;
            }
            
            ShapeHeader.Write(shpBinaryWriter);

            // assumes Geometry type of the first item will the same for all other items in the collection.
            
            shxHeader.Write(shxBinaryWriter);

            // write the individual records.
            int _pos = 50; // header length in WORDS
            for (int i = 0; i < numShapes; i++)
            {
                body = Layer.Features[i].BasicGeometry;
                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();
            shxBinaryWriter.Close();
            shpBinaryWriter.Flush();
            shpBinaryWriter.Close();

        }
Ejemplo n.º 9
0
        //[InlineData(@"LPC_Individual_Landmark_and_Historic_Building_Database\LPC_Individual_Landmark_and_Historic_Building_Database")]
        public void Shape_OutputFeatures_Borough_Boundaries(string shapeFilePath)
        {
            string shapeDirectory = $"../../../../../Files/{shapeFilePath}";
            string shapePath      = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), shapeDirectory));

            GeometryFactory     factory             = new();
            ShapefileDataReader shapeFileDataReader = new(shapePath, factory);

            ShapefileHeader shpHeader = shapeFileDataReader.ShapeHeader;

            _testOutputHelper.WriteLine($"Shape type: {shpHeader.ShapeType}");

            //Display the min and max bounds of the shapefile
            var bounds = shpHeader.Bounds;

            _testOutputHelper.WriteLine($"Min bounds: ({bounds.MinX},{bounds.MinY})");
            _testOutputHelper.WriteLine($"Max bounds: ({bounds.MaxX},{bounds.MaxY})");

            //Display summary information about the Dbase file
            DbaseFileHeader header = shapeFileDataReader.DbaseHeader;

            _testOutputHelper.WriteLine("Dbase info");
            _testOutputHelper.WriteLine($"{header.Fields.Length} Columns, {header.NumRecords} Records");

            for (int i = 0; i < header.NumFields; i++)
            {
                DbaseFieldDescriptor fldDescriptor = header.Fields[i];
                _testOutputHelper.WriteLine($"   {fldDescriptor.Name} {fldDescriptor.DbaseType}");
            }

            // Read through all records of the shapefile (geometry and attributes) into a feature collection
            var features = new List <Feature>();

            while (shapeFileDataReader.Read())
            {
                Feature         feature         = new();
                AttributesTable attributesTable = new();

                string[] keys     = new string[header.NumFields];
                var      geometry = shapeFileDataReader.Geometry;

                for (int i = 0; i < header.NumFields; i++)
                {
                    DbaseFieldDescriptor fldDescriptor = header.Fields[i];
                    keys[i] = fldDescriptor.Name;

                    // First Field Geometry
                    var value = shapeFileDataReader.GetValue(i + 1);
                    attributesTable.Add(fldDescriptor.Name, value);
                }

                feature.Geometry   = geometry;
                feature.Attributes = attributesTable;
                features.Add(feature);
            }

            var result = features;

            foreach (var f in features)
            {
                var z = f.Geometry.Contains(new Point(1032999, 217570));
                if (z)
                {
                    var z1 = f.Attributes["pct"];
                    //var z2 = f.Attributes["patrol_bor"];
                    //var z3 = f.Attributes["sector"];
                }
            }
        }
Ejemplo n.º 10
0
        public ShapefileHeader GetShapeProperties()
        {
            ShapefileHeader shpHeader = ShapeFileDataReader.ShapeHeader;

            return(shpHeader);
        }
Ejemplo n.º 11
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(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.ComputeRequiredLengthInWords(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 = 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 = 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.ComputeRequiredLengthInWords(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);
        }