public static void WriteFeaturesToShapefile(string filename, List <Feature> features) { if (File.Exists(filename + ".shp")) { File.Delete(filename + ".shp"); } if (File.Exists(filename + ".dbf")) { File.Delete(filename + ".dbf"); } if (File.Exists(filename + ".shx")) { File.Delete(filename + ".shx"); } if (features.Count == 0) { return; } var outGeomFactory = GeometryFactory.Default; var writer = new ShapefileDataWriter(filename, outGeomFactory); var outDbaseHeader = ShapefileDataWriter.GetHeader(features[0], features.Count); writer.Header = outDbaseHeader; writer.Write(features); }
static void WriteBuildingsToShapefile(string fileName, List <NetTopologySuite.Features.Feature> buildings) { if (File.Exists(fileName + ".shp")) { File.Delete(fileName + ".shp"); } if (File.Exists(fileName + ".dbf")) { File.Delete(fileName + ".dbf"); } if (File.Exists(fileName + ".dbf")) { File.Delete(fileName + ".dbf"); } if (buildings.Count == 0) { return; } var outGeoFactory = NetTopologySuite.Geometries.GeometryFactory.Default; var writer = new ShapefileDataWriter(fileName, outGeoFactory); var outDBaseHeader = ShapefileDataWriter.GetHeader(buildings[0], buildings.Count); writer.Header = outDBaseHeader; writer.Write(buildings); }
public bool ConvertJsonToShapeFileNew(string json, string shapeFilePath, string namefile) { string geometryString = ConvertGeometryToString(json); var attributesTable = new NetTopologySuite.Features.AttributesTable(); var attributes = AddAttribute(json); var geomFactory = new NetTopologySuite.Geometries.GeometryFactory(new NetTopologySuite.Geometries.PrecisionModel(), 4326); var wktReader = new WKTReader(geomFactory); var geometry = wktReader.Read(geometryString); string filesPathName = shapeFilePath.Substring(0, shapeFilePath.Length - 4); removeShapeFileIfExists(filesPathName); if (attributes != null) { attributesTable = attributes; var features = new List <NetTopologySuite.Features.IFeature> { new NetTopologySuite.Features.Feature(geometry, attributesTable) }; var name = namefile.Substring(0, namefile.Length - 4); // Create the directory where we will save the shapefile //var shapeFilePath = Path.Combine(Server.MapPath("~/Document"), name); if (!Directory.Exists(filesPathName)) { Directory.CreateDirectory(filesPathName); } // Construct the shapefile name. Don't add the .shp extension or the ShapefileDataWriter will // produce an unwanted shapefile var shapeFileName = Path.Combine(filesPathName, name); var shapeFilePrjName = Path.Combine(filesPathName, $"{name}.prj"); // Create the shapefile var outGeomFactory = NetTopologySuite.Geometries.GeometryFactory.Default; var writer = new ShapefileDataWriter(shapeFileName, outGeomFactory, Encoding.UTF8); var outDbaseHeader = ShapefileDataWriter.GetHeader(features[0], features.Count, Encoding.UTF8); writer.Header = outDbaseHeader; writer.Write(features); // Create the projection file using (var streamWriter = new StreamWriter(shapeFilePrjName)) { streamWriter.Write(GeographicCoordinateSystem.WGS84.WKT); } System.IO.File.WriteAllText(Path.Combine(filesPathName, $"{name}.cpg"), Encoding.UTF8.HeaderName); //var shapeFileReader = new ShapefileDataReader(shapeFileName, NetTopologySuite.Geometries.GeometryFactory.Default, Encoding.UTF8); //var read = shapeFileReader.Read(); //var values = new object[shapeFileReader.FieldCount - 1]; //var a = values[1]; //var a1 = shapeFileReader.GetName(0); //var geom = shapeFileReader.Geometry; string zipName = filesPathName + ".zip"; CompressToZipFile(new List <string>() { shapeFileName + ".shp", shapeFileName + ".dbf", shapeFileName + ".prj", shapeFileName + ".shx", shapeFileName + ".cpg" }, zipName); return(true); } return(false); }
private static void ExportFeatures(List <IFeature> pFeatures, string pFileName, bool pIsMainFile) { if (pFeatures.Count == 0) { CDebug.Warning("You are trying to export 0 features"); return; } string shapeFileFolder = pIsMainFile ? CProjectData.outputFolder : CProjectData.outputTileSubfolder; shapeFileFolder += "/shp_" + pFileName; Directory.CreateDirectory(shapeFileFolder); //create subfolder // Construct the shapefile name. Don't add the .shp extension or the ShapefileDataWriter will // produce an unwanted shapefile string shapeFileName = Path.Combine(shapeFileFolder, pFileName); string shapeFilePrjName = Path.Combine(shapeFileFolder, $"{pFileName}.prj"); // Create the shapefile var outGeomFactory = GeometryFactory.Default; var writer = new ShapefileDataWriter(shapeFileName, outGeomFactory); var outDbaseHeader = ShapefileDataWriter.GetHeader(pFeatures[0], pFeatures.Count); writer.Header = outDbaseHeader; writer.Write(pFeatures); //Create the projection file using (var streamWriter = new StreamWriter(shapeFilePrjName)) { streamWriter.Write(GeographicCoordinateSystem.WGS84.WKT); } }
// see https://code.google.com/p/nettopologysuite/issues/detail?id=146 public void Issue146_ShapeCreationWithInvalidAttributeName() { var points = new Coordinate[3]; points[0] = new Coordinate(0, 0); points[1] = new Coordinate(1, 0); points[2] = new Coordinate(1, 1); var ls = new LineString(points); var mls = GeometryFactory.Default.CreateMultiLineString(new ILineString[] { ls }); var attrs = new AttributesTable(); attrs.Add("Simulation name", "FOO"); var features = new[] { new Feature(mls, attrs) }; ShapefileDataWriter shp_writer = null; Assert.Throws <ArgumentException>(() => shp_writer = new ShapefileDataWriter("invalid_line_string") { Header = ShapefileDataWriter.GetHeader(features[0], features.Length) }); //Assert.Throws<ArgumentException>(() => shp_writer.Write(features)); }
public void WriteShouldWorkWithoutIndexFileWhenRequested() { var pt = GeometryFactory.Default.CreatePoint(new Coordinate(2, 3)); var attributes = new AttributesTable { { "Foo", "Bar" } }; Feature[] features = { new Feature(pt, attributes) }; string baseFileName = TestContext.CurrentContext.Test.ID; string shpFilePath = baseFileName + ".shp"; string dbfFilePath = baseFileName + ".dbf"; string shxFilePath = baseFileName + ".shx"; var reg = new ShapefileStreamProviderRegistry( shapeStream: new FileStreamProvider(StreamTypes.Shape, shpFilePath), dataStream: new FileStreamProvider(StreamTypes.Data, dbfFilePath), indexStream: null, validateShapeProvider: true, validateDataProvider: true, validateIndexProvider: false); var wr = new ShapefileDataWriter(reg, GeometryFactory.Default, CodePagesEncodingProvider.Instance.GetEncoding(1252)); wr.Header = ShapefileDataWriter.GetHeader(features[0], features.Length); wr.Write(features); Assert.True(File.Exists(shpFilePath)); Assert.True(File.Exists(dbfFilePath)); Assert.False(File.Exists(shxFilePath)); }
private void TestShapeCreation() { var points = new Coordinate[3]; points[0] = new Coordinate(0, 0); points[1] = new Coordinate(1, 0); points[2] = new Coordinate(1, 1); var line_string = new LineString(points); var attributes = new AttributesTable(); attributes.AddAttribute("FOO", "FOO"); var feature = new Feature(Factory.CreateMultiLineString(new ILineString[] { line_string }), attributes); var features = new Feature[1]; features[0] = feature; var shp_writer = new ShapefileDataWriter("line_string") { Header = ShapefileDataWriter.GetHeader(features[0], features.Length) }; shp_writer.Write(features); }
static void Main(string[] args) { // let's show you what's going on. OsmSharp.Logging.Logger.LogAction = (origin, level, message, parameters) => { Console.WriteLine(string.Format("[{0}] {1} - {2}", origin, level, message)); }; Download.ToFile("http://files.itinero.tech/data/OSM/planet/europe/luxembourg-latest.osm.pbf", "luxembourg-latest.osm.pbf").Wait(); using (var fileStream = File.OpenRead("luxembourg-latest.osm.pbf")) { // create source stream. var source = new PBFOsmStreamSource(fileStream); // show progress. var progress = source.ShowProgress(); // filter all powerlines and keep all nodes. var filtered = from osmGeo in progress where osmGeo.Type == OsmSharp.OsmGeoType.Node || (osmGeo.Type == OsmSharp.OsmGeoType.Way && osmGeo.Tags != null && osmGeo.Tags.Contains("power", "line")) select osmGeo; // convert to a feature stream. // WARNING: nodes that are partof powerlines will be kept in-memory. // it's important to filter only the objects you need **before** // you convert to a feature stream otherwise all objects will // be kept in-memory. var features = filtered.ToFeatureSource(); // filter out only linestrings. var lineStrings = from feature in features where feature.Geometry is LineString select feature; // build feature collection. var featureCollection = new FeatureCollection(); var attributesTable = new AttributesTable { { "type", "powerline" } }; foreach (var feature in lineStrings) { // make sure there is a constant # of attributes with the same names before writing the shapefile. featureCollection.Add(new Feature(feature.Geometry, attributesTable)); } // convert to shape. var header = ShapefileDataWriter.GetHeader(featureCollection.Features.First(), featureCollection.Features.Count); var shapeWriter = new ShapefileDataWriter("luxembourg.shp", new GeometryFactory()) { Header = header }; shapeWriter.Write(featureCollection.Features); } }
public static void CreateShpFile(Feature polygone, List <Feature> points) { GeometryFactory outGeomFactory = new GeometryFactory(); string folderPath = Path.Combine("..\\..\\..\\data\\", polygone.Attributes["name"].ToString()); System.IO.Directory.CreateDirectory(folderPath); ShapefileDataWriter writer = new ShapefileDataWriter($"{folderPath}/{polygone.Attributes["name"]}", outGeomFactory); DbaseFileHeader outDbaseHeader = ShapefileDataWriter.GetHeader((Feature)points[0], points.Count); writer.Header = outDbaseHeader; writer.Write(points); }
/// <summary> /// Executes the actual algorithm. /// </summary> protected override void DoRun() { // assumed here all arguments are as they should be. var features = new FeaturesList(_routerDb, _profiles); var header = ShapefileDataWriter.GetHeader(features[0], features.Count); var shapeWriter = new ShapefileDataWriter(_fileName, new GeometryFactory()) { Header = header }; shapeWriter.Write(features); this.HasSucceeded = true; }
public void shapefile_with_empty_attributes_table_should_not_thrown_errors() { IFeature feature = new Feature(new Point(0, 0), new AttributesTable()); IList <IFeature> features = new List <IFeature> { feature }; string path = CreateShapefilePath(); var header = ShapefileDataWriter.GetHeader(feature, features.Count); var writer = new ShapefileDataWriter(path) { Header = header }; writer.Write(features); Assert.That(File.Exists(Path.ChangeExtension(path, ".shp")), Is.True); }
/// <summary> /// Executes the actual algorithm. /// </summary> public void Run(CancellationToken cancellationToken) { // assumed here all arguments are as they should be. var features = new FeaturesList(_routerDb); if (features.Count == 0) { return; } var header = ShapefileDataWriter.GetHeader(features[0], features.Count); var shapeWriter = new ShapefileDataWriter(_fileName, new GeometryFactory()) { Header = header }; shapeWriter.Write(features); }
public Stream WriteShape(IList <Feature> featureCollection, string name, DbaseFileHeader header = null) { if (featureCollection.IsEmpty()) { return(null); } ShapeMemoryStreamDataWriter shapeWriter = new ShapeMemoryStreamDataWriter(GISService.CreateGeometryFactory()); shapeWriter.Header = header == null?ShapefileDataWriter.GetHeader(featureCollection.First(), featureCollection.Count) : header; shapeWriter.Write(featureCollection as IList); MemoryStream shpMemStream = shapeWriter.GetShpStream(); MemoryStream shxMemStream = shapeWriter.GetShxStream(); MemoryStream dbfMemStream = shapeWriter.GetDbfStream(); MemoryStream prjMemStream = new MemoryStream(Encoding.UTF8.GetBytes(GisConstants.EsriWkt21781)); MemoryStream cpgMemStream = new MemoryStream(Encoding.UTF8.GetBytes(GisConstants.EsriUTF8CodePage)); ZipFile zipfile = new ZipFile(); shpMemStream.Seek(0, 0); shxMemStream.Seek(0, 0); dbfMemStream.Seek(0, 0); prjMemStream.Seek(0, 0); zipfile.AddEntry(name + ".shp", shpMemStream); zipfile.AddEntry(name + ".shx", shxMemStream); zipfile.AddEntry(name + ".dbf", dbfMemStream); zipfile.AddEntry(name + ".prj", prjMemStream); zipfile.AddEntry(name + ".cpg", cpgMemStream); MemoryStream stream = new MemoryStream(); zipfile.Save(stream); stream.Seek(0, 0); shpMemStream.Close(); shxMemStream.Close(); dbfMemStream.Close(); prjMemStream.Close(); return(stream); }
// see https://code.google.com/p/nettopologysuite/issues/detail?id=146 public void Issue146_ShapeCreationWithInvalidAttributeName() { Coordinate[] points = new Coordinate[3]; points[0] = new Coordinate(0, 0); points[1] = new Coordinate(1, 0); points[2] = new Coordinate(1, 1); LineString ls = new LineString(points); IMultiLineString mls = GeometryFactory.Default.CreateMultiLineString(new ILineString[] { ls }); AttributesTable attrs = new AttributesTable(); attrs.AddAttribute("Simulation name", "FOO"); Feature[] features = new[] { new Feature(mls, attrs) }; ShapefileDataWriter shp_writer = new ShapefileDataWriter("invalid_line_string") { Header = ShapefileDataWriter.GetHeader(features[0], features.Length) }; shp_writer.Write(features); }
public void Create(List <RadioInfo> list, string outputName, string projection) { var features = new List <IFeature>(); foreach (RadioInfo radio in list) { /////// var attributesTable = new AttributesTable(); if (radio.Geometry != null) { attributesTable.AddAttribute("Redcode", radio.Redcode); attributesTable.AddAttribute("IsValid", radio.Geometry.IsValid); attributesTable.AddAttribute("Points", radio.Geometry.Coordinates.Count()); attributesTable.AddAttribute("AreaKm2", radio.Geometry.Area * 1000 * 1000); attributesTable.AddAttribute("Polygons", radio.Polygon.Count); attributesTable.AddAttribute("PerimeterKm", radio.TotalPerimeter * 1000); GeometryFactory fc = new GeometryFactory(); var geo = radio.Geometry; features.Add(new Feature(geo, attributesTable)); } else { Console.WriteLine("Empty geometry: " + radio.Redcode); } } // Create the shapefile var outGeomFactory = GeometryFactory.Default; var writer = new ShapefileDataWriter(Context.ResolveFilename(outputName), outGeomFactory); var outDbaseHeader = ShapefileDataWriter.GetHeader(features[0], features.Count); writer.Header = outDbaseHeader; writer.Write(features); // Create the projection file using (var streamWriter = new StreamWriter(Context.ResolveFilename(outputName + ".prj"))) { streamWriter.Write(projection); } }
public void SaveNodesToShape(string shapeFileName, Dictionary <long, GeoNode> allNodesCache, List <GeoNode> nodesToSave) { string firstNameAttribute = "a"; string lastNameAttribute = "b"; //create geometry factory IGeometryFactory geomFactory = NtsGeometryServices.Instance.CreateGeometryFactory(); IList <Feature> features = new List <Feature>(); for (int i = 0; i < nodesToSave.Count - 1; i++) { GeoNode node1 = nodesToSave[i]; GeoNode node2 = nodesToSave[i + 1]; //var ngbGeoNode = allNodesCache[ngb.NodeId]; var line = geomFactory.CreateLineString(new[] { new Coordinate(node1.Longitude, node1.Latitude), new Coordinate(node2.Longitude, node2.Latitude) }); AttributesTable t1 = new AttributesTable(); t1.AddAttribute(firstNameAttribute, node1.OSMId); t1.AddAttribute(lastNameAttribute, node2.OSMId); Feature feat = new Feature(line, t1); features.Add(feat); } var dirName = Path.GetDirectoryName(shapeFileName); if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } var writer = new ShapefileDataWriter(shapeFileName) { Header = ShapefileDataWriter.GetHeader(features[0], features.Count) }; writer.Write(features); }
public void Test() { var features = new List <IFeature>(); var seq = DotSpatialAffineCoordinateSequenceFactory.Instance.Create(1, Ordinates.XY); seq.SetOrdinate(0, Ordinate.X, -91.0454); seq.SetOrdinate(0, Ordinate.Y, 32.5907); var pt = new GeometryFactory(DotSpatialAffineCoordinateSequenceFactory.Instance).CreatePoint(seq); var attr = new AttributesTable(); attr.Add("FirstName", "John"); attr.Add("LastName", "Doe"); features.Add(new Feature(pt, attr)); string fileName = Path.GetTempFileName(); fileName = fileName.Substring(0, fileName.Length - 4); var shpWriter = new ShapefileDataWriter(fileName, features[0].Geometry.Factory) { Header = ShapefileDataWriter.GetHeader(features[0], features.Count) }; shpWriter.Write(features); bool isTrue; using (var reader = new ShapefileDataReader(fileName, pt.Factory)) @isTrue = reader.ShapeHeader.ShapeType.ToString() == "Point"; foreach (string file in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(fileName) + ".*")) { File.Delete(file); } Assert.IsTrue(@isTrue); }
/// <summary> /// xy列表直接输出到shape文件 /// </summary> /// <param name="polygonXYList">x1 y1,x2 y2,x3 y3,x4 y4</param> /// <param name="bw"></param> public static void ExportShapeFile(string path, List <string> polygonXYList) { try { ShapefileDataWriter shapeWrite = new ShapefileDataWriter(path); IGeometryFactory pGFactory = new GeometryFactory(); IList <Feature> featureList = new List <Feature>(); foreach (string str in polygonXYList) { List <Coordinate> coordList = new List <Coordinate>(); string[] xys = str.Split(','); string name = xys[0]; AttributesTable at = new AttributesTable(); at.AddAttribute("TFH", name); for (int i = 1; i < xys.Length; i++) { string[] xandy = xys[i].Split(' '); double x = 0, y = 0; double.TryParse(xandy[0], out x); double.TryParse(xandy[1], out y); Coordinate coord = new Coordinate(x, y); coordList.Add(coord); } IPolygon pPolygon = pGFactory.CreatePolygon(coordList.ToArray()); Feature f = new Feature(pPolygon, at); featureList.Add(f); } System.Collections.IList features = (System.Collections.IList)featureList; shapeWrite.Header = ShapefileDataWriter.GetHeader(featureList[0], featureList.Count); shapeWrite.Write(features); } catch (Exception ex) { throw ex; } }
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); }
private void ReadFromShapeFile() { var featureCollection = new List <IFeature>(); const string filename = @"country"; if (!File.Exists(filename + ".dbf")) { throw new FileNotFoundException(filename + " not found at " + Environment.CurrentDirectory); } var dataReader = new ShapefileDataReader(filename, new GeometryFactory()); while (dataReader.Read()) { var feature = new Feature { Geometry = dataReader.Geometry }; var length = dataReader.DbaseHeader.NumFields; var keys = new string[length]; for (var i = 0; i < length; i++) { keys[i] = dataReader.DbaseHeader.Fields[i].Name; } feature.Attributes = new AttributesTable(); for (var i = 0; i < length; i++) { var val = dataReader.GetValue(i); feature.Attributes.AddAttribute(keys[i], val); } featureCollection.Add(feature); } var index = 0; Console.WriteLine("Elements = " + featureCollection.Count); foreach (IFeature feature in featureCollection) { Console.WriteLine("Feature " + index++); var table = feature.Attributes as AttributesTable; foreach (var name in table.GetNames()) { Console.WriteLine(name + ": " + table[name]); } } //Directory var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format(@"..{0}..{0}..{0}NetTopologySuite.Samples.Shapefiles{0}", Path.DirectorySeparatorChar)); // Test write with stub header var file = dir + "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"); } var dataWriter = new ShapefileDataWriter(file); dataWriter.Header = ShapefileDataWriter.GetHeader(featureCollection[0] as IFeature, featureCollection.Count); dataWriter.Write(featureCollection); // Test write with header from a existing shapefile file = dir + "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) { Header = ShapefileDataWriter.GetHeader(dir + "country.dbf") }; dataWriter.Write(featureCollection); }
private void TestWriteZMValuesShapeFile(bool testM) { var points = new Coordinate[3]; points[0] = new Coordinate(0, 0); points[1] = new Coordinate(1, 0); points[2] = new Coordinate(1, 1); var csFactory = DotSpatialAffineCoordinateSequenceFactory.Instance; var sequence = csFactory.Create(3, Ordinates.XYZM); for (int i = 0; i < 3; i++) { sequence.SetOrdinate(i, Ordinate.X, points[i].X); sequence.SetOrdinate(i, Ordinate.Y, points[i].Y); sequence.SetOrdinate(i, Ordinate.Z, 1 + i); if (testM) { sequence.SetOrdinate(i, Ordinate.M, 11 + i); } } var lineString = Factory.CreateLineString(sequence); var attributes = new AttributesTable(); attributes.Add("FOO", "Trond"); var feature = new Feature(Factory.CreateMultiLineString(new[] { lineString }), attributes); var features = new Feature[1]; features[0] = feature; var shpWriter = new ShapefileDataWriter("ZMtest", Factory) { Header = ShapefileDataWriter.GetHeader(features[0], features.Length) }; shpWriter.Write(features); // Now let's read the file and verify that we got Z and M back var factory = new GeometryFactory(DotSpatialAffineCoordinateSequenceFactory.Instance); using (var reader = new ShapefileDataReader("ZMtest", factory)) { reader.Read(); var geom = reader.Geometry; for (int i = 0; i < 3; i++) { var c = geom.Coordinates[i]; Assert.AreEqual(i + 1, c.Z); } if (testM) { sequence = ((ILineString)geom).CoordinateSequence; for (int i = 0; i < 3; i++) { Assert.AreEqual(sequence.GetOrdinate(i, Ordinate.M), 11 + i); } } // Run a simple attribute test too string v = reader.GetString(1); Assert.AreEqual(v, "Trond"); } }
public void TestGetHeaderFromFeature() { var feature = new Feature(new Point(0, 0), new AttributesTable()); feature.Attributes.AddAttribute("c_long", (long)12345678900000000); feature.Attributes.AddAttribute("c_ulong", (ulong)12345678900000000); feature.Attributes.AddAttribute("c_int", int.MinValue); feature.Attributes.AddAttribute("c_uint", uint.MinValue); feature.Attributes.AddAttribute("c_short", short.MaxValue); feature.Attributes.AddAttribute("c_ushort", ushort.MaxValue); feature.Attributes.AddAttribute("c_string", string.Empty); feature.Attributes.AddAttribute("c_double", double.MinValue); feature.Attributes.AddAttribute("c_bool", false); feature.Attributes.AddAttribute("c_datetime", new DateTime(1999, 01, 01)); var header = ShapefileDataWriter.GetHeader(feature, 1); Assert.IsNotNull(header); Assert.AreEqual(10, header.Fields.Length); var field = header.Fields.FirstOrDefault(x => x.Name == "c_long"); Assert.IsNotNull(field); Assert.AreEqual(78, field.DbaseType); Assert.AreEqual(0, field.DecimalCount); Assert.AreEqual(18, field.Length); field = header.Fields.FirstOrDefault(x => x.Name == "c_ulong"); Assert.IsNotNull(field); Assert.AreEqual(78, field.DbaseType); Assert.AreEqual(0, field.DecimalCount); Assert.AreEqual(18, field.Length); field = header.Fields.FirstOrDefault(x => x.Name == "c_int"); Assert.IsNotNull(field); Assert.AreEqual(78, field.DbaseType); Assert.AreEqual(0, field.DecimalCount); Assert.AreEqual(10, field.Length); field = header.Fields.FirstOrDefault(x => x.Name == "c_uint"); Assert.IsNotNull(field); Assert.AreEqual(78, field.DbaseType); Assert.AreEqual(0, field.DecimalCount); Assert.AreEqual(10, field.Length); field = header.Fields.FirstOrDefault(x => x.Name == "c_short"); Assert.IsNotNull(field); Assert.AreEqual(78, field.DbaseType); Assert.AreEqual(0, field.DecimalCount); Assert.AreEqual(10, field.Length); field = header.Fields.FirstOrDefault(x => x.Name == "c_ushort"); Assert.IsNotNull(field); Assert.AreEqual(78, field.DbaseType); Assert.AreEqual(0, field.DecimalCount); Assert.AreEqual(10, field.Length); field = header.Fields.FirstOrDefault(x => x.Name == "c_string"); Assert.IsNotNull(field); Assert.AreEqual(67, field.DbaseType); Assert.AreEqual(0, field.DecimalCount); Assert.AreEqual(254, field.Length); field = header.Fields.FirstOrDefault(x => x.Name == "c_double"); Assert.IsNotNull(field); Assert.AreEqual(78, field.DbaseType); Assert.AreEqual(8, field.DecimalCount); Assert.AreEqual(18, field.Length); field = header.Fields.FirstOrDefault(x => x.Name == "c_bool"); Assert.IsNotNull(field); Assert.AreEqual(76, field.DbaseType); Assert.AreEqual(0, field.DecimalCount); Assert.AreEqual(1, field.Length); field = header.Fields.FirstOrDefault(x => x.Name == "c_datetime"); Assert.IsNotNull(field); Assert.AreEqual(68, field.DbaseType); Assert.AreEqual(0, field.DecimalCount); Assert.AreEqual(8, field.Length); }
private void button1_Click(object sender, EventArgs e) { //initial vars string futureFieldSector = "Sector"; string futureFieldName = "ID"; string futureIE = "IE"; string futureFieldAreaCG = "Sup Mas"; string futureFieldLegalCG = "Sup Acte"; string futureFieldTitle = "Titlu"; string futureFieldTarla = "Tarla"; string futureFieldParcel = "Parcela"; string futurePerson = "Persoana"; string futureDead = "Decedat"; string futureIntravilan = "Intra"; string futureImprejmuit = "Ingradit"; int nrCGXML = 0; int intr = 0; //Create a future list IList <Feature> futuresList = new List <Feature>(); IList <Feature> CladirifuturesList = new List <Feature>(); //browse string filePath = textBox1.Text; string[] filez = Directory.GetFiles(filePath, "*.cgxml", SearchOption.AllDirectories); var files = filez.Select(x => new FileInfo(x)).ToArray(); for (int i = 0; i < (int)files.Length; i++) { nrCGXML++; } //loop trough cgxml for (int i = 0; i < (int)files.Length; i++) { FileInfo fo = files[i]; CGXML fisier = new CGXML(); try { fisier.ReadXml(fo.FullName); } catch (Exception exception) { Exception ex = exception; MessageBox.Show(string.Concat(new string[] { "Eroare ", ex.GetType().ToString(), "\n", ex.Message, fo.FullName })); } //create geometry factory GeometryFactory geomFactory = NtsGeometryServices.Instance.CreateGeometryFactory(); GeometryFactory fabricaGeometri = NtsGeometryServices.Instance.CreateGeometryFactory(); Geometry[] gr = new Geometry[nrCGXML]; List <Geometry> geometrieCladiri = new List <Geometry>(); Dictionary <int, List <Coordinate> > BCoordinates = new Dictionary <int, List <Coordinate> >(); foreach (CGXML.PointsRow pr in fisier.Points) { if (pr.BuildingRow == null) { continue; } if (!BCoordinates.ContainsKey(pr.BUILDINGID)) { BCoordinates.Add(pr.BUILDINGID, new List <Coordinate>()); } else { BCoordinates[pr.BUILDINGID].Add(new Coordinate(pr.X, pr.Y)); } } int indexCladire = 0; foreach (CGXML.LandRow lr in fisier.Land) { // List<Coordinate> bCoord = new List<Coordinate>(); foreach (CGXML.BuildingRow br in fisier.Building) { AttributesTable Btable = new AttributesTable(); Btable.Add(futureFieldSector, lr.CADSECTOR); Btable.Add(futureFieldName, lr.CADGENNO); Btable.Add("nrCladire", br.BUILDNO); Btable.Add("destCladire", br.BUILDINGDESTINATION); //Geometry //bCoord = bCoord.Where(c => c != null).ToArray(); if (BCoordinates[indexCladire + 1].First() != BCoordinates[indexCladire + 1].Last()) { BCoordinates[indexCladire + 1].Add(BCoordinates[indexCladire + 1].First()); } geometrieCladiri.Add(fabricaGeometri.CreatePolygon(BCoordinates[indexCladire + 1].ToArray())); //gr[indexCladire] = geomFactory.CreatePolygon( BCoordinates[indexCladire].ToArray()); CladirifuturesList.Add(new Feature(geometrieCladiri[indexCladire], Btable)); indexCladire++; } var r = 0; string Person = ""; var q = 0; int v = 0; string intratest = ""; string ie = lr.E2IDENTIFIER; string imprej = (lr.ENCLOSED ? "DA" : "NU").ToString(); int parcelCount = fisier.Parcel.Count; string[] titleNO = new string[parcelCount]; string[] landLotNO = new string[parcelCount]; string[] parcelNO = new string[parcelCount]; List <bool> intraNO = new List <bool>(); string intraString = ""; Coordinate[] myCoord = new Coordinate[fisier.Points.Count + 1]; string[] personArr = new string[fisier.Person.Count]; string[] deadPersonArr = new string[fisier.Person.Count]; string sector = lr.CADSECTOR.ToString(); foreach (CGXML.PointsRow pr in fisier.Points) { if (pr.IMMOVABLEID != 9898989) { myCoord[r++] = new Coordinate(pr.X, pr.Y); } } if (myCoord[r - 1] != myCoord[0]) { myCoord[r] = myCoord[0]; } foreach (CGXML.PersonRow pp in fisier.Person) { personArr[q] = string.Concat(pp.FIRSTNAME, " ", pp.LASTNAME); deadPersonArr[q] = (pp.DEFUNCT ? "DA" : "NU"); q++; } foreach (CGXML.ParcelRow pr in fisier.Parcel) { titleNO[v] = pr.TITLENO; landLotNO[v] = pr.LANDPLOTNO; parcelNO[v] = pr.PARCELNO; intraNO.Add(pr.INTRAVILAN); v++; } string[] titleNO2 = titleNO.Distinct().ToArray(); titleNO2 = titleNO2.Where(f => f != null).ToArray(); string[] landLotNO2 = landLotNO.Distinct().ToArray(); landLotNO2 = landLotNO2.Where(p => p != null).ToArray(); string[] parcelNo2 = parcelNO.Distinct().ToArray(); parcelNo2 = parcelNO.Where(l => l != null).ToArray(); string titleNO3 = string.Join(" , ", titleNO2); string landLotNO3 = string.Join(" , ", landLotNO2); string parcelNO3 = string.Join(" , ", parcelNo2); if (!intraNO.Contains(false) && intraNO.Contains(true)) { intraString = "Intra"; } else if (intraNO.Contains(false) && !intraNO.Contains(true)) { intraString = "Extra"; } else { intraString = "Mixt"; } string personTest = string.Join(" , ", personArr); string deadPesTest = string.Join(" , ", deadPersonArr); //create the default table with fields - alternately use DBaseField classes AttributesTable t = new AttributesTable(); t.Add(futureFieldSector, lr.CADSECTOR); t.Add(futureFieldName, lr.CADGENNO); t.Add(futureIE, lr.E2IDENTIFIER); t.Add(futureFieldAreaCG, lr.MEASUREDAREA); t.Add(futureFieldLegalCG, lr.PARCELLEGALAREA); t.Add(futurePerson, personTest); t.Add(futureDead, deadPesTest); t.Add(futureFieldTitle, titleNO3); t.Add(futureFieldTarla, landLotNO3); t.Add(futureFieldParcel, parcelNO3); t.Add(futureImprejmuit, imprej); t.Add(futureIntravilan, intraString); //Geometry myCoord = myCoord.Where(c => c != null).ToArray(); gr[intr] = geomFactory.CreatePolygon(myCoord); futuresList.Add(new Feature(gr[intr], t)); intr++; } indexCladire = 0; } //Feature list IList <Feature> features = futuresList.OfType <Feature>().ToList(); string shapefile = string.Concat(filePath, "\\", "Imobile"); ShapefileDataWriter writer = new ShapefileDataWriter(shapefile) { Header = ShapefileDataWriter.GetHeader(features[0], features.Count) }; writer.Write(features); //Cladiri Feature list IList <Feature> Cladirifeatures = CladirifuturesList.OfType <Feature>().ToList(); string Cladirishapefile = string.Concat(filePath, "\\", "Cladiri"); ShapefileDataWriter Cladiriwriter = new ShapefileDataWriter(shapefile) { Header = ShapefileDataWriter.GetHeader(Cladirifeatures[0], Cladirifeatures.Count) }; Cladiriwriter.Write(Cladirifeatures); }
private void ReadFromShapeFile() { var featureCollection = new List <IFeature>(); const string filename = @"country"; if (!File.Exists(filename + ".dbf")) { throw new FileNotFoundException(filename + " not found at " + Environment.CurrentDirectory); } var dataReader = new ShapefileDataReader(filename, new GeometryFactory()); while (dataReader.Read()) { var feature = new 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.Add(keys[i], val); } featureCollection.Add(feature); } int index = 0; Console.WriteLine("Elements = " + featureCollection.Count); foreach (var feature in featureCollection) { Console.WriteLine("Feature " + index++); var table = feature.Attributes as AttributesTable; foreach (string name in table.GetNames()) { Console.WriteLine(name + ": " + table[name]); } } //Directory string dir = CommonHelpers.TestShapefilesDirectory + Path.DirectorySeparatorChar; // Test write with stub header string file = dir + "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"); } var dataWriter = new ShapefileDataWriter(file); dataWriter.Header = ShapefileDataWriter.GetHeader(featureCollection[0] as IFeature, featureCollection.Count); dataWriter.Write(featureCollection); // Test write with header from a existing shapefile file = dir + "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) { Header = ShapefileDataWriter.GetHeader(dir + "country.dbf") }; dataWriter.Write(featureCollection); }
public void exportShpfile(DataTable DTTable) { // Create the directory where we will save the shapefile var shapeFilePath = @"D:\JYA_dev\Sriver_FM_NetTopology_TEST\" + roundName; if (!Directory.Exists(shapeFilePath)) { Directory.CreateDirectory(shapeFilePath); } // Construct the shapefile name. Don't add the .shp extension or the ShapefileDataWriter will produce an unwanted shapefile var shapeFileName = Path.Combine(shapeFilePath, roundName); var shapeFilePrjName = Path.Combine(shapeFilePath, $"{roundName}.prj"); var geomFactory = new GeometryFactory(new PrecisionModel(), 5186); var wktReader = new WKTReader(geomFactory); var feature_point = new Feature(); var feature_line = new Feature(); var feature_polygon = new Feature(); var features_point_list = new List <IFeature>(wktPoint.Length); var features_line_list = new List <IFeature>(wktLine.Length); var features_polygon_list = new List <IFeature>(wktPolygon.Length); //AttributesTable attributesTable = new AttributesTable(); for (int i = 0; i < wktPoint.Length; i++) { AttributesTable attributesTable = new AttributesTable(); attributesTable.Add("Point_id", DTTable.Rows[wktPointID[i]]["Point_id"]); attributesTable.Add("River_id", DTTable.Rows[wktPointID[i]]["River_id"]); attributesTable.Add("Round_id", DTTable.Rows[wktPointID[i]]["Round_id"]); attributesTable.Add("Snap_id", DTTable.Rows[wktPointID[i]]["Snap_id"]); attributesTable.Add("Img_id", DTTable.Rows[wktPointID[i]]["Img_id"]); attributesTable.Add("Img_lat", DTTable.Rows[wktPointID[i]]["Img_lat"]); attributesTable.Add("Img_lon", DTTable.Rows[wktPointID[i]]["Img_lon"]); attributesTable.Add("Img_height", DTTable.Rows[wktPointID[i]]["Img_height"]); attributesTable.Add("Img_roll", DTTable.Rows[wktPointID[i]]["Img_roll"]); attributesTable.Add("Img_pitch", DTTable.Rows[wktPointID[i]]["Img_pitch"]); attributesTable.Add("Img_heading", DTTable.Rows[wktPointID[i]]["Img_heading"]); attributesTable.Add("Fm_class", DTTable.Rows[wktPointID[i]]["Fm_class"]); attributesTable.Add("Shape_class", DTTable.Rows[wktPointID[i]]["Shape_class"]); attributesTable.Add("Num_point", DTTable.Rows[wktPointID[i]]["Num_point"]); features_point_list.Add(feature_point); } for (int i = 0; i < wktLine.Length; i++) { AttributesTable attributesTable = new AttributesTable(); attributesTable.Add("Point_id", DTTable.Rows[wktLineID[i]]["Point_id"]); attributesTable.Add("River_id", DTTable.Rows[wktLineID[i]]["River_id"]); attributesTable.Add("Round_id", DTTable.Rows[wktLineID[i]]["Round_id"]); attributesTable.Add("Snap_id", DTTable.Rows[wktLineID[i]]["Snap_id"]); attributesTable.Add("Img_id", DTTable.Rows[wktLineID[i]]["Img_id"]); attributesTable.Add("Img_lat", DTTable.Rows[wktLineID[i]]["Img_lat"]); attributesTable.Add("Img_lon", DTTable.Rows[wktLineID[i]]["Img_lon"]); attributesTable.Add("Img_height", DTTable.Rows[wktLineID[i]]["Img_height"]); attributesTable.Add("Img_roll", DTTable.Rows[wktLineID[i]]["Img_roll"]); attributesTable.Add("Img_pitch", DTTable.Rows[wktLineID[i]]["Img_pitch"]); attributesTable.Add("Img_heading", DTTable.Rows[wktLineID[i]]["Img_heading"]); attributesTable.Add("Fm_class", DTTable.Rows[wktLineID[i]]["Fm_class"]); attributesTable.Add("Shape_class", DTTable.Rows[wktLineID[i]]["Shape_class"]); attributesTable.Add("Num_point", DTTable.Rows[wktLineID[i]]["Num_point"]); try { feature_line = new Feature(wktReader.Read(wktLine[i]), attributesTable); // Console.WriteLine($" {DTTable.Rows[wktLineID[i]]["Point_id"]} : {wktLine[i]}"); } catch { //Console.WriteLine($"wkt : {wktLine[i]}"); } features_line_list.Add(feature_line); } for (int i = 0; i < wktPolygon.Length; i++) { AttributesTable attributesTable = new AttributesTable(); attributesTable.Add("Point_id", DTTable.Rows[wktPolygonID[i]]["Point_id"]); attributesTable.Add("River_id", DTTable.Rows[wktPolygonID[i]]["River_id"]); attributesTable.Add("Round_id", DTTable.Rows[wktPolygonID[i]]["Round_id"]); attributesTable.Add("Snap_id", DTTable.Rows[wktPolygonID[i]]["Snap_id"]); attributesTable.Add("Img_id", DTTable.Rows[wktPolygonID[i]]["Img_id"]); attributesTable.Add("Img_lat", DTTable.Rows[wktPolygonID[i]]["Img_lat"]); attributesTable.Add("Img_lon", DTTable.Rows[wktPolygonID[i]]["Img_lon"]); attributesTable.Add("Img_height", DTTable.Rows[wktPolygonID[i]]["Img_height"]); attributesTable.Add("Img_roll", DTTable.Rows[wktPolygonID[i]]["Img_roll"]); attributesTable.Add("Img_pitch", DTTable.Rows[wktPolygonID[i]]["Img_pitch"]); attributesTable.Add("Img_heading", DTTable.Rows[wktPolygonID[i]]["Img_heading"]); attributesTable.Add("Fm_class", DTTable.Rows[wktPolygonID[i]]["Fm_class"]); attributesTable.Add("Shape_class", DTTable.Rows[wktPolygonID[i]]["Shape_class"]); attributesTable.Add("Num_point", DTTable.Rows[wktPolygonID[i]]["Num_point"]); feature_polygon = new Feature(wktReader.Read(wktPolygon[i]), attributesTable); features_polygon_list.Add(feature_polygon); } // Create the shapefile var outGeomFactory = GeometryFactory.Default; var writer_point = new ShapefileDataWriter(shapeFileName + "_point", outGeomFactory); var writer_line = new ShapefileDataWriter(shapeFileName + "_line", outGeomFactory); var writer_polygon = new ShapefileDataWriter(shapeFileName + "_polygon", outGeomFactory); //test if (features_line_list.Count > 0) { var outDbaseHeaderLine = ShapefileDataWriter.GetHeader(features_line_list[0], features_line_list.Count); writer_line.Header = outDbaseHeaderLine; } else { writer_line.Header = new DbaseFileHeader(); } if (features_point_list.Count > 0) { var outDbaseHeaderPoint = ShapefileDataWriter.GetHeader(features_point_list[0], features_point_list.Count); writer_point.Header = outDbaseHeaderPoint; } else { writer_point.Header = new DbaseFileHeader(); } if (features_polygon_list.Count > 0) { var outDbaseHeaderPolygon = ShapefileDataWriter.GetHeader(features_polygon_list[0], features_polygon_list.Count); writer_polygon.Header = outDbaseHeaderPolygon; } else { writer_polygon.Header = new DbaseFileHeader(); } writer_point.Write(features_point_list); writer_line.Write(features_line_list); writer_polygon.Write(features_polygon_list); // Create the projection file using (var streamWriter = new StreamWriter(shapeFilePrjName)) { streamWriter.Write(GeographicCoordinateSystem.WGS84.WKT); } Console.WriteLine("Writing Shp files is Compelted."); }
private void button3_Click(object sender, EventArgs e) { if (this.listBox1.Visible != true) { this.listBox1.Visible = true; } string sector = ""; //browse FolderBrowserDialogEx CostumFolderBrowserDialog = new FolderBrowserDialogEx(); string Titlu = "Alege Dosarul cu CGXML'uri"; CostumFolderBrowserDialog.Title = Titlu; CostumFolderBrowserDialog.StartPosition = FormStartPosition.CenterParent; DialogResult dr = CostumFolderBrowserDialog.ShowDialog(this); if (dr == DialogResult.OK) { CostumFolderBrowserDialogPath = CostumFolderBrowserDialog.SelectedPath; } string[] filez = Directory.GetFiles(CostumFolderBrowserDialogPath.ToString(), "*.cgxml", SearchOption.AllDirectories); NumericComparer ns = new NumericComparer(); System.Array.Sort(filez, ns); var files = filez.Select(x => new FileInfo(x)).ToArray(); //initial vars string futureFieldName = "ID"; string futureFieldAreaCG = "Sup Mas"; string futureFieldLegalCG = "Sup Acte"; string futurePerson = "Persoana"; int nrCGXML = 0; int intr = 0; for (int i = 0; i < (int)files.Length; i++) { nrCGXML++; } //Create a future list IList <Feature> futuresList = new List <Feature>(); //loop trough cgxml for (int i = 0; i < (int)files.Length; i++) { FileInfo fo = files[i]; CGXML fisier = new CGXML(); try { fisier.ReadXml(fo.FullName); } catch (Exception exception) { Exception ex = exception; MessageBox.Show(string.Concat(new string[] { "Eroare ", ex.GetType().ToString(), "\n", ex.Message, fo.FullName })); } //create geometry factory IGeometryFactory geomFactory = NtsGeometryServices.Instance.CreateGeometryFactory(); IGeometry[] gr = new IGeometry[nrCGXML]; foreach (CGXML.LandRow lr in fisier.Land) { var r = 0; string Person = ""; var q = 0; Coordinate[] myCoord = new Coordinate[fisier.Points.Count + 1]; string[] personArr = new string[fisier.Person.Count]; sector = lr.CADSECTOR.ToString(); foreach (CGXML.PointsRow pr in fisier.Points) { if (pr.IMMOVABLEID != 9898989) { myCoord[r++] = new Coordinate(pr.X, pr.Y); } } if (myCoord[r - 1] != myCoord[0]) { myCoord[r] = myCoord[0]; } foreach (CGXML.PersonRow pp in fisier.Person) { personArr[q++] = string.Concat(pp.FIRSTNAME, " ", pp.LASTNAME); } //create the default table with fields - alternately use DBaseField classes AttributesTable t = new AttributesTable(); t.AddAttribute(futureFieldName, lr.CADGENNO); t.AddAttribute(futureFieldAreaCG, lr.MEASUREDAREA); t.AddAttribute(futureFieldLegalCG, lr.PARCELLEGALAREA); t.AddAttribute(futurePerson, personArr[0]); //Geometry myCoord = myCoord.Where(c => c != null).ToArray(); gr[intr] = geomFactory.CreatePolygon(myCoord); futuresList.Add(new Feature(gr[intr], t)); intr++; } } //Feature list IList <Feature> features = futuresList.OfType <Feature>().ToList(); string shapefile = string.Concat(CostumFolderBrowserDialogPath, "\\", "Imobile ", sector); ShapefileDataWriter writer = new ShapefileDataWriter(shapefile) { Header = ShapefileDataWriter.GetHeader(features[0], features.Count) }; writer.Write(features); System.Diagnostics.Process.Start("explorer.exe", CostumFolderBrowserDialogPath); }
public async Task <IActionResult> GenerateFile() { var data = await _context.Profiles.Select(p => new { p.FirstName, p.LastName, p.Latitude, p.Longitude, p.CompanyName, p.IsDropOffPoint, p.Phone, p.IsRequestor, p.IsSupplier, }).ToListAsync(); var geomFactory = NtsGeometryServices.Instance.CreateGeometryFactory(); var features = new List <Feature>(); var faker = new Bogus.Faker("en"); foreach (var d in data) { //note that attribute names can be at most 11 characters var t1 = new AttributesTable { { "firstName", d.FirstName ?? "" }, { "lastName", d.LastName ?? "" }, { "companyName", d.CompanyName ?? "" }, { "dropOff", d.IsDropOffPoint.GetValueOrDefault().ToString() }, { "type", DetermineType(d.IsRequestor, d.IsSupplier) }, { "phoneNumber", d.Phone ?? "" }, { "amount1", faker.Random.Number(100, 10000) }, { "product1", faker.Commerce.ProductName() } }; Geometry g1 = geomFactory.CreatePoint(new Coordinate(d.Longitude, d.Latitude)); var feat1 = new Feature(g1, t1); features.Add(feat1); } var shapeFileFolder = GetShapeFilePath(); var zipPath = GetZipFilePath(); var shapefileName = Path.Combine(shapeFileFolder, "maker"); var writer = new ShapefileDataWriter(shapefileName) { Header = ShapefileDataWriter.GetHeader(features[0], features.Count) }; writer.Write(features); if (System.IO.File.Exists(zipPath)) { System.IO.File.Delete(zipPath); } ZipFile.CreateFromDirectory(shapeFileFolder, zipPath, CompressionLevel.Fastest, false); await using (var csvWriter = new StreamWriter(GetCSVFilePath())) await using (var csv = new CsvWriter(csvWriter, CultureInfo.InvariantCulture)) { csv.WriteRecords(data); } return(Ok($"Files created and zipped to {zipPath}")); }
public static void CreateShpFile(List <IFeature> features, string path) { //// Wkt in 4326 SRID (WGS84) ////var wkt = "POLYGON ((-86.7605020509258 41.5101338613656, -86.7604972038273 41.5100611525915, -86.7604971708084 41.5100606308085, -86.7604611720717 41.5094596307695, -86.7604611426546 41.5094591103497, -86.7604291439208 41.5088571103154, -86.760429130715 41.508856853856, -86.7603991319814 41.5082548538241, -86.7603991259966 41.5082547317887, -86.7603701303631 41.5076537960468, -86.7603401446338 41.5070530565908, -86.7603071566895 41.5064532528163, -86.7603071500912 41.506453131098, -86.7602814240795 41.5059715533315, -86.7605549835241 41.5059607024218, -86.7605808466407 41.5064448078787, -86.760613844555 41.5070447469854, -86.7606138651484 41.5070451395365, -86.7606438664126 41.5076461395046, -86.7606438727239 41.5076462680791, -86.7606728710439 41.5082472070294, -86.7607028628788 41.5088490177453, -86.7607348434949 41.5094506292495, -86.7607708135428 41.5100511081057, -86.760776407335 41.5101350123382, -86.7605020509258 41.5101338613656))"; //var wkt = "LINESTRING ("; //for(int i=0; i<coords.Count(); i++) //{ // if (i > 0) wkt += ", "; // wkt += (string)(coords[i].X).ToString().Replace(",", ".").Replace(".", ".") + " " + coords[i].Y.ToString().Replace(",", ".").Replace(".", "."); //} //wkt += ")"; //var geomFactory = new GeometryFactory(new PrecisionModel(), 4326); //var wktReader = new WKTReader(geomFactory); //var geometry = wktReader.Read(wkt); ////Debug.WriteLine($"Geometry Type: {geometry.GeometryType}"); ////Debug.WriteLine($"Shapefile Type: {Shapefile.GetShapeType(geometry)}"); ////IPolygon geomPolygon = geometry as IPolygon; //var attributesTable = new AttributesTable(); //var features = new List<IFeature> //{ // new Feature(geometry, attributesTable) //}; // Create the directory where we will save the shapefile var shapeFilePath = path; string[] pathTab = path.Split("\\"); var name = pathTab.Last(); //var shapeFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); if (!Directory.Exists(shapeFilePath)) { Directory.CreateDirectory(shapeFilePath); } // Construct the shapefile name. Don't add the .shp extension or the ShapefileDataWriter will // produce an unwanted shapefile var shapeFileName = Path.Combine(shapeFilePath, name); var shapeFilePrjName = Path.Combine(shapeFilePath, $"{name}.prj"); // Create the shapefile var outGeomFactory = GeometryFactory.Default; var writer = new ShapefileDataWriter(shapeFileName, outGeomFactory); var outDbaseHeader = ShapefileDataWriter.GetHeader(features[0], features.Count); writer.Header = outDbaseHeader; writer.Write(features); // Create the projection file using (var streamWriter = new StreamWriter(shapeFilePrjName)) { streamWriter.Write(GeographicCoordinateSystem.WGS84.WKT); } //var shapeFileReader = new ShapefileDataReader(shapeFileName, GeometryFactory.Default); //var read = shapeFileReader.Read(); //var geom = shapeFileReader.Geometry; }
public static void Compress(string shapeFilePath, int gridFieldIndex, string encoding = null, string outputShapeFileName = "") { var factory = new GeometryFactory(); if (!File.Exists(shapeFilePath)) { Console.WriteLine("文件不存在。"); return; } string filePath = Path.GetDirectoryName(shapeFilePath); string outputShapeFilePath = ""; var outputFilePath = Path.ChangeExtension(shapeFilePath, ".text"); if (!string.IsNullOrEmpty(outputShapeFileName)) { outputShapeFilePath = Path.Combine(filePath, outputShapeFileName); outputFilePath = Path.ChangeExtension(outputShapeFileName, ".txt"); } var nFile = new FileStream(outputFilePath, FileMode.Create); Encoding fileEncoding = Encoding.UTF8; nFile.Position = nFile.Length; var fts = new List <IFeature>(); ShapefileDataReader reader; if (string.IsNullOrEmpty(encoding)) { reader = new ShapefileDataReader(shapeFilePath, factory); } else { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); reader = new ShapefileDataReader(shapeFilePath, factory, Encoding.GetEncoding(encoding)); } using (reader) { var dict = new Dictionary <string, IGeometry>(); int count = 0; long recordCount = 0; try { while (reader.Read()) { recordCount++; var gridId = reader.GetString(gridFieldIndex); if (dict.ContainsKey(gridId)) { continue; } count++; if (count % 1000 == 0) { Console.WriteLine($"{count}"); nFile.Flush(); } dict.Add(gridId, reader.Geometry); string text = $"{gridId},{reader.Geometry.ToString()}\n"; var bytes = fileEncoding.GetBytes(text); nFile.Write(bytes, 0, bytes.Length); var attrs = new AttributesTable(); attrs.Add("GRIDID", gridId); var feature = new Feature(reader.Geometry, attrs); fts.Add(feature); } } catch (Exception) { Console.WriteLine($"第{recordCount}条记录读取错误!"); throw; } Console.WriteLine($"共处理{reader.RecordCount}条数据,压缩生成{count}条数据"); nFile.Close(); }; if (!string.IsNullOrEmpty(outputShapeFilePath)) { var writer = new ShapefileDataWriter(outputShapeFilePath, factory); writer.Header = ShapefileDataWriter.GetHeader(fts[0], fts.Count); writer.Write(fts); } Console.WriteLine("成功结束!"); }