public void BuildStradeFixed() { string path = "strade" + shp; Assert.IsTrue(File.Exists(path)); ShapefileDataReader reader = new ShapefileDataReader(path, factory); List<Feature> features = new List<Feature>(reader.RecordCount); while (reader.Read()) { Feature feature = new Feature(reader.Geometry, new AttributesTable()); object[] values = new object[reader.FieldCount - 1]; reader.GetValues(values); for (int i = 0; i < values.Length; i++) { string name = reader.GetName(i + 1); object value = values[i]; feature.Attributes.AddAttribute(name, value); } features.Add(feature); } Assert.AreEqual(703, features.Count); string shapepath = "strade_fixed"; if (File.Exists(shapepath + shp)) File.Delete(shapepath + shp); Assert.IsFalse(File.Exists(shapepath + shp)); if (File.Exists(shapepath + shx)) File.Delete(shapepath + shx); Assert.IsFalse(File.Exists(shapepath + shx)); if (File.Exists(shapepath + dbf)) File.Delete(shapepath + dbf); Assert.IsFalse(File.Exists(shapepath + dbf)); DbaseFileHeader header = reader.DbaseHeader; ShapefileDataWriter writer = new ShapefileDataWriter(shapepath, factory); writer.Header = header; writer.Write(features); Assert.IsTrue(File.Exists(shapepath + shp)); Assert.IsTrue(File.Exists(shapepath + shx)); Assert.IsTrue(File.Exists(shapepath + dbf)); }
/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <returns></returns> private IGeometry CheckShapefile(string fileName) { int count = 0; IGeometry current = null; IGeometry result = null; using (ShapefileDataReader reader = new ShapefileDataReader(fileName, GeometryFactory.Fixed)) { while (reader.Read()) { current = reader.Geometry; if (!current.IsValid) { Debug.WriteLine("Imvalid geometry found: " + current); continue; } if (result == null) result = current; else result = result.Union(current); Debug.WriteLine("Iteration => " + ++count); } } Debug.WriteLine("Operation result: " + result); return result; }
private void ReadFromShapeFile() { ArrayList featureCollection = new ArrayList(); string filename = @"country"; if (!File.Exists(filename + ".dbf")) throw new FileNotFoundException(filename + " not found at " + Environment.CurrentDirectory); ShapefileDataReader dataReader = new ShapefileDataReader(filename, new GeometryFactory()); while (dataReader.Read()) { Feature feature = new Feature(); feature.Geometry = dataReader.Geometry; int length = dataReader.DbaseHeader.NumFields; string[] keys = new string[length]; for (int i = 0; i < length; i++) keys[i] = dataReader.DbaseHeader.Fields[i].Name; feature.Attributes = new AttributesTable(); for (int i = 0; i < length; i++) { object val = dataReader.GetValue(i); feature.Attributes.AddAttribute(keys[i], val); } featureCollection.Add(feature); } int index = 0; Console.WriteLine("Elements = " + featureCollection.Count); foreach (Feature feature in featureCollection) { Console.WriteLine("Feature " + index++); AttributesTable table = feature.Attributes as AttributesTable; foreach (string name in table.GetNames()) Console.WriteLine(name + ": " + table[name]); } // Test write with stub header string file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"../../../NetTopologySuite.Samples.Shapefiles/testWriteStubHeader"); if (File.Exists(file + ".shp")) File.Delete(file + ".shp"); if (File.Exists(file + ".shx")) File.Delete(file + ".shx"); if (File.Exists(file + ".dbf")) File.Delete(file + ".dbf"); ShapefileDataWriter dataWriter = new ShapefileDataWriter(file); dataWriter.Header = ShapefileDataWriter.GetHeader(featureCollection[0] as Feature, featureCollection.Count); dataWriter.Write(featureCollection); // Test write with header from a existing shapefile file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"../../../NetTopologySuite.Samples.Shapefiles/testWriteShapefileHeader"); if (File.Exists(file + ".shp")) File.Delete(file + ".shp"); if (File.Exists(file + ".shx")) File.Delete(file + ".shx"); if (File.Exists(file + ".dbf")) File.Delete(file + ".dbf"); dataWriter = new ShapefileDataWriter(file); dataWriter.Header = ShapefileDataWriter.GetHeader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"../../../NetTopologySuite.Samples.Shapefiles/country.dbf")); dataWriter.Write(featureCollection); }
public void TestReadingCrustalTestShapeFile() { // Original file with characters '°' in NAME field. using (ShapefileDataReader reader = new ShapefileDataReader("crustal_test_bugged", Factory)) { int length = reader.DbaseHeader.NumFields; while (reader.Read()) { Debug.WriteLine(reader.GetValue(length - 1)); } } // Removed NAME field characters using (ShapefileDataReader reader = new ShapefileDataReader("crustal_test", Factory)) { int length = reader.DbaseHeader.NumFields; while (reader.Read()) { Debug.WriteLine(reader.GetValue(length - 1)); } } }
private void askGeometry(string filename, string epsg) { try { GeometryFactory f = new GeometryFactory(new PrecisionModel(), Convert.ToInt16(epsg)); using (ShapefileDataReader dr = new ShapefileDataReader(filename, f)) { if (dr.RecordCount > 0) { if (dr.ShapeHeader.ShapeType.ToString() == "Polygon") { while (dr.Read()) { _polygons.Add((IPolygon)dr.Geometry); } } else { throw new Exception("Geometry type is not Polygon"); } } else { throw new Exception("The selected shapefile does not contain any row"); } } } catch (Exception ex) { throw ex; } }
/// <summary> /// /// </summary> /// <param name="parent"></param> public ShapefileDataReaderEnumerator(ShapefileDataReader parent) { _parent = parent; _parent.Reset(); }
/// <summary> /// Returns an ShapefileDataReader representing the data in a shapefile. /// </summary> /// <param name="filename">The filename (minus the . and extension) to read.</param> /// <param name="geometryFactory">The geometry factory to use when creating the objects.</param> /// <returns>An ShapefileDataReader representing the data in the shape file.</returns> public static ShapefileDataReader CreateDataReader(string filename, GeometryFactory geometryFactory) { if (filename == null) throw new ArgumentNullException("filename"); if (geometryFactory == null) throw new ArgumentNullException("geometryFactory"); ShapefileDataReader shpDataReader= new ShapefileDataReader(filename,geometryFactory); return shpDataReader; }
/// <summary> /// Creates a DataTable representing the information in a shape file. /// </summary> /// <param name="filename">The filename (minus the . and extension) to read.</param> /// <param name="tableName">The name to give to the table.</param> /// <param name="geometryFactory">The geometry factory to use when creating the objects.</param> /// <returns>DataTable representing the data </returns> public static DataTable CreateDataTable(string filename, string tableName, GeometryFactory geometryFactory) { if (filename == null) throw new ArgumentNullException("filename"); if (tableName == null) throw new ArgumentNullException("tableName"); if (geometryFactory == null) throw new ArgumentNullException("geometryFactory"); ShapefileDataReader shpfileDataReader= new ShapefileDataReader(filename, geometryFactory); DataTable table = new DataTable(tableName); // use ICustomTypeDescriptor to get the properies/ fields. This way we can get the // length of the dbase char fields. Because the dbase char field is translated into a string // property, we lost the length of the field. We need to know the length of the // field when creating the table in the database. IEnumerator enumerator = shpfileDataReader.GetEnumerator(); bool moreRecords = enumerator.MoveNext(); ICustomTypeDescriptor typeDescriptor = (ICustomTypeDescriptor) enumerator.Current; foreach (PropertyDescriptor property in typeDescriptor.GetProperties()) { ColumnStructure column = (ColumnStructure) property; Type fieldType = column.PropertyType; DataColumn datacolumn = new DataColumn(column.Name, fieldType); if (fieldType== typeof(string)) // use MaxLength to pass the length of the field in the dbase file datacolumn.MaxLength=column.Length; table.Columns.Add( datacolumn ); } // add the rows - need a do-while loop because we read one row in order to determine the fields int iRecordCount = 0; object[] values = new object[shpfileDataReader.FieldCount]; do { iRecordCount++; shpfileDataReader.GetValues(values); table.Rows.Add(values); moreRecords = enumerator.MoveNext(); } while (moreRecords); return table; }
// If you select the ICustomTypeDescriptor implemented by RowStructure into a // property grid, the values are somehow missing, so copy them over to a class // that works. private AdhocPropertyList CreatePropertyList(ShapefileDataReader sfdr) { object[] vals = new object[sfdr.FieldCount-1]; // ignore the geometry column sfdr.GetValues(vals); AdhocPropertyList result = new AdhocPropertyList(vals.Length); for(int i=0; i<vals.Length; i++) { string name = sfdr.GetName(i+1); // yes it's +1 result.Add(new AdhocProperty(name, vals[i], true, true)); // but the value isn't! } return result; }
private static void ConvertCalles(string input, string output, Func<string, int, bool> filter) { var nodes = new Dictionary<Coordinate, int>(); var calles = new Dictionary<int, Calle>(); var vias = new ShapefileDataReader (input, new GeometryFactory ()); while (vias.Read ()) { var multiline = vias.Geometry as MultiLineString; if (multiline == null) throw new NotSupportedException (); var departamento = vias.GetInt32(CodigoDepartamento); var nombre = vias.GetString(NombreCalle); if(filter(nombre, departamento)) continue; var codigo = vias.GetInt32(CodigoNombre); var sentido = vias.GetInt32(Sentido); Calle calle; if(!calles.TryGetValue(codigo, out calle)) { calle = new Calle { Nombre = nombre }; calles[codigo] = calle; } foreach (var geometry in multiline) { if (geometry == multiline) continue; var line = geometry as LineString; if (line == null) throw new NotSupportedException (); var wayNodes = new List<int>(); foreach (Coordinate coord in line.Coordinates) { coord.X = (float)coord.X; coord.Y = (float)coord.Y; int node; if(!nodes.TryGetValue(coord, out node)) { nodes[coord] = node = nodes.Count; } wayNodes.Add(node); } if (sentido < 0) wayNodes.Reverse(); calle.Add(wayNodes, sentido != 0); } } SaveToOsm(nodes, calles, output + ".osm"); }