### Install OsmSharp Packages Source: https://context7.com/osmsharp/core/llms.txt Use the .NET CLI to add the core library and geometry support packages to your project. ```bash # Core library dotnet add package OsmSharp # Geometry support with NTS dotnet add package OsmSharp.Geo ``` -------------------------------- ### Write OSM-PBF Files Source: https://context7.com/osmsharp/core/llms.txt Use PBFOsmStreamTarget to write OSM data to PBF format. Initialize the target and call Flush/Close to finalize the file. ```csharp using OsmSharp; using OsmSharp.Streams; using OsmSharp.Tags; using System; using System.IO; using var fileStream = File.Open("output.osm.pbf", FileMode.Create, FileAccess.ReadWrite); var target = new PBFOsmStreamTarget(fileStream, compress: true); target.Initialize(); // Add a node target.AddNode(new Node { Id = 1, Latitude = 51.5074, Longitude = -0.1278, Tags = new TagsCollection( new Tag("name", "London"), new Tag("place", "city")), Version = 1, Visible = true, TimeStamp = DateTime.UtcNow, UserId = 1, UserName = "mapper", ChangeSetId = 1 }); // Add a way target.AddWay(new Way { Id = 100, Nodes = new long[] { 1, 2, 3, 4, 1 }, Tags = new TagsCollection( new Tag("building", "yes"), new Tag("name", "Example Building")), Version = 1, Visible = true }); // Add a relation target.AddRelation(new Relation { Id = 1000, Members = new[] { new RelationMember(100, "outer", OsmGeoType.Way), new RelationMember(101, "inner", OsmGeoType.Way) }, Tags = new TagsCollection( new Tag("type", "multipolygon"), new Tag("landuse", "residential")), Version = 1, Visible = true }); target.Flush(); target.Close(); ``` -------------------------------- ### Write OSM PBF File Stream Source: https://github.com/osmsharp/core/blob/develop/README.md This snippet demonstrates how to write OSM data to a PBF file. It includes initializing the target, adding a node with tags, and flushing the stream. ```csharp using(var fileStream = new FileInfo(@"/path/to/my/osmfile.osm.pbf").OpenRead()) { var target = new PBFOsmStreamTarget(fileStream); target.Initialize(); target.AddNode(new Node() { Id = 1, ChangeSetId = 1, Latitude = 0, Longitude = 0, Tags = new TagsCollection( Tag.Create("key", "value")), TimeStamp = DateTime.Now, UserId = 1424, UserName = "you", Version = 1, Visible = true }); target.Flush(); target.Close(); } ``` -------------------------------- ### Extract and Export Power Lines to GeoJSON Source: https://context7.com/osmsharp/core/llms.txt Reads a PBF file, filters for power lines, converts them to geometries, and exports to GeoJSON. Requires NetTopologySuite for geometry handling. Ensure the input PBF file exists. ```csharp using NetTopologySuite.Features; using NetTopologySuite.Geometries; using OsmSharp; using OsmSharp.Geo; using OsmSharp.Logging; using OsmSharp.Streams; using System; using System.IO; using System.Linq; class Program { static void Main() { // Setup logging Logger.LogAction = (origin, level, message, _) => Console.WriteLine($"[{origin}] {level}: {message}"); using var fileStream = File.OpenRead("luxembourg-latest.osm.pbf"); var source = new PBFOsmStreamSource(fileStream); var progress = source.ShowProgress(); // Filter power lines (keep nodes for geometry construction) var filtered = from element in progress where element.Type == OsmGeoType.Node || (element.Type == OsmGeoType.Way && element.Tags != null && element.Tags.Contains("power", "line")) select element; // Convert to feature source var features = filtered.ToFeatureSource(); // Build GeoJSON feature collection var collection = new FeatureCollection(); foreach (var feature in features.Where(f => f.Geometry is LineString)) { collection.Add(feature); } // Export to GeoJSON var serializer = NetTopologySuite.IO.GeoJsonSerializer.Create(); using var writer = new StringWriter(); serializer.Serialize(writer, collection); File.WriteAllText("powerlines.geojson", writer.ToString()); Console.WriteLine($"Exported {collection.Count} power lines to powerlines.geojson"); } } ``` -------------------------------- ### Write OSM-XML Files Source: https://context7.com/osmsharp/core/llms.txt Use XmlOsmStreamTarget to write data to standard OSM XML format. Ensure the target is initialized before adding elements. ```csharp using OsmSharp; using OsmSharp.Streams; using OsmSharp.Tags; using System.IO; using var fileStream = File.Open("output.osm", FileMode.Create); var target = new XmlOsmStreamTarget(fileStream) { Generator = "MyOsmApp" }; target.Initialize(); target.AddNode(new Node { Id = 1, Latitude = 48.8566, Longitude = 2.3522, Tags = new TagsCollection(new Tag("name", "Paris")), Version = 1, Visible = true }); target.Flush(); target.Close(); // Output: Standard OSM XML format with declaration and root ``` -------------------------------- ### Monitor Processing Progress with ShowProgress Source: https://context7.com/osmsharp/core/llms.txt The ShowProgress extension method reports processing progress to the configured logger. Ensure Logger.LogAction is configured to receive progress updates. This is useful for long-running stream operations. ```csharp using OsmSharp; using OsmSharp.Logging; using OsmSharp.Streams; using System; using System.IO; using System.Linq; // Configure logging Logger.LogAction = (origin, level, message, parameters) => { Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] [{origin}] {level}: {message}"); }; using var fileStream = File.OpenRead("planet.osm.pbf"); var source = new PBFOsmStreamSource(fileStream); // Add progress reporting var progress = source.ShowProgress(); // Filter with progress feedback var highways = from element in progress where element.Type == OsmGeoType.Way && element.Tags != null && element.Tags.ContainsKey("highway") select element; var count = highways.Count(); Console.WriteLine($"Found {count} highways"); // Output: // [14:23:45] [StreamProgress] verbose: Pass 1 - Node[100000] @ 125000/s // [14:23:46] [StreamProgress] verbose: Pass 1 - Node[200000] @ 130000/s // ... ``` -------------------------------- ### Read OSM-PBF Files Source: https://context7.com/osmsharp/core/llms.txt Use PBFOsmStreamSource to stream data from large PBF files. The source must be iterated to process nodes, ways, and relations. ```csharp using OsmSharp; using OsmSharp.Streams; using System; using System.IO; // Read all elements from a PBF file using var fileStream = File.OpenRead("region.osm.pbf"); var source = new PBFOsmStreamSource(fileStream); foreach (var element in source) { switch (element.Type) { case OsmGeoType.Node: var node = element as Node; Console.WriteLine($"Node {node.Id}: ({node.Latitude}, {node.Longitude})"); break; case OsmGeoType.Way: var way = element as Way; Console.WriteLine($"Way {way.Id}: {way.Nodes?.Length ?? 0} nodes"); break; case OsmGeoType.Relation: var relation = element as Relation; Console.WriteLine($"Relation {relation.Id}: {relation.Members?.Length ?? 0} members"); break; } } ``` -------------------------------- ### Read OSM PBF File Stream Source: https://github.com/osmsharp/core/blob/develop/README.md Use this snippet to read data from an OSM PBF file and enumerate all objects. Ensure the file path is correct. ```csharp using(var fileStream = new FileInfo(@"/path/to/some/osmfile.osm.pbf").OpenRead()) { var source = new PBFOsmStreamSource(fileStream); foreach (var element in source) { Console.WriteLine(element.ToString()); } } ``` -------------------------------- ### Convert OSM stream to complete objects in C# Source: https://github.com/osmsharp/core/blob/develop/samples/Sample.CompleteStream/README.md Use this pattern to resolve references in OSM data. Ensure filtering is applied before calling ToComplete to prevent excessive memory usage. ```csharp using (var fileStream = File.OpenRead("path/to/file.osm.pbf")) { // create source stream. var source = new PBFOsmStreamSource(fileStream); // filter all powerlines and keep all nodes. var filtered = from osmGeo in source where osmGeo.Type == OsmSharp.OsmGeoType.Node || (osmGeo.Type == OsmSharp.OsmGeoType.Way && osmGeo.Tags != null && osmGeo.Tags.Contains("power", "line")) select osmGeo; // convert to complete 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 complete stream otherwise all objects will // be kept in-memory. var complete = filtered.ToComplete(); } ``` -------------------------------- ### Apply OSM Changesets to Data Stream Source: https://context7.com/osmsharp/core/llms.txt Applies OSM change files to an existing data stream. Ensure the input stream contains valid OSM data. ```csharp using OsmSharp; using OsmSharp.Changesets; using OsmSharp.Streams; using System.IO; // Create a changeset var changeset = new OsmChange { Generator = "MyApp", Version = 0.6, Create = new OsmGeo[] { new Node { Id = -1, // Negative ID for new objects Latitude = 51.5, Longitude = -0.1, Version = 1 } }, Modify = new OsmGeo[] { new Node { Id = 12345, Latitude = 51.51, Longitude = -0.11, Version = 2 } }, Delete = new OsmGeo[] { new Node { Id = 99999, Version = 3 } } }; // Apply changeset to a stream using var fileStream = File.OpenRead("region.osm.pbf"); var source = new PBFOsmStreamSource(fileStream); var updated = source.ApplyChanges(changeset); // Process updated stream foreach (var element in updated) { // Elements reflect applied changes } ``` -------------------------------- ### Filter OSM objects by contributor using Linq Source: https://github.com/osmsharp/core/blob/develop/samples/Sample.Filter/README.md Uses a PBFOsmStreamSource to stream data and applies a Linq query to filter objects by the UserName property. ```csharp using (var fileStream = File.OpenRead("path/to/file.osm.pbf")) { // create source stream. var source = new PBFOsmStreamSource(fileStream); // let's use linq to leave only objects last touched by the given mapper. var filtered = from osmGeo in source where osmGeo.UserName == "Javier GutiƩrrez" select osmGeo; ... } ``` -------------------------------- ### Convert to Complete Objects Source: https://context7.com/osmsharp/core/llms.txt Converts partial OSM objects into complete objects with fully instantiated nodes. Note that this operation keeps filtered nodes in memory. ```csharp using OsmSharp; using OsmSharp.Complete; using OsmSharp.Streams; using System; using System.IO; using System.Linq; using var fileStream = File.OpenRead("region.osm.pbf"); var source = new PBFOsmStreamSource(fileStream); // Filter power lines and keep all nodes var filtered = from element in source where element.Type == OsmGeoType.Node || (element.Type == OsmGeoType.Way && element.Tags != null && element.Tags.Contains("power", "line")) select element; // Convert to complete objects - ways will have actual Node objects // WARNING: Filtered nodes are kept in memory to build complete ways var complete = filtered.ToComplete(); foreach (var element in complete) { if (element is CompleteWay way) { Console.WriteLine($"Power line {way.Id} has {way.Nodes.Length} nodes:"); foreach (var node in way.Nodes) { Console.WriteLine($" Node {node.Id}: ({node.Latitude}, {node.Longitude})"); } } } ``` -------------------------------- ### Read OSM-XML Files Source: https://context7.com/osmsharp/core/llms.txt Use XmlOsmStreamSource to process OSM data in XML format. Note that the stream may need to be reset if multiple passes are required. ```csharp using OsmSharp; using OsmSharp.Streams; using System.IO; using System.Linq; // Read from OSM XML file using var fileStream = File.OpenRead("region.osm"); var source = new XmlOsmStreamSource(fileStream); // Count elements by type var nodes = source.Where(e => e.Type == OsmGeoType.Node).Count(); source.Reset(); var ways = source.Where(e => e.Type == OsmGeoType.Way).Count(); source.Reset(); var relations = source.Where(e => e.Type == OsmGeoType.Relation).Count(); Console.WriteLine($"Nodes: {nodes}, Ways: {ways}, Relations: {relations}"); ``` -------------------------------- ### Manage OSM Tags with TagsCollection Source: https://context7.com/osmsharp/core/llms.txt The TagsCollection class manages key-value pairs for OSM object attributes. It allows for creating, accessing, modifying, and iterating through tags. Tags can be added, replaced, or removed by key. ```csharp using OsmSharp; using OsmSharp.Tags; using System; // Create tags from constructor var tags = new TagsCollection( new Tag("name", "Main Street"), new Tag("highway", "primary"), new Tag("maxspeed", "50"), new Tag("surface", "asphalt") ); // Access and modify tags Console.WriteLine($"Name: {tags.GetValue("name")}"); Console.WriteLine($"Has highway tag: {tags.ContainsKey("highway")}"); Console.WriteLine($"Is primary road: {tags.Contains("highway", "primary")}"); // Add or replace tags tags.AddOrReplace(new Tag("lanes", "2")); tags.AddOrReplace(new Tag("maxspeed", "60")); // Updates existing // Remove tags tags.RemoveKey("surface"); // Iterate all tags foreach (var tag in tags) { Console.WriteLine($"{tag.Key} = {tag.Value}"); } // Create node with tags var node = new Node { Id = 12345, Latitude = 52.5200, Longitude = 13.4050, Tags = new TagsCollection( new Tag("name", "Berlin"), new Tag("capital", "yes"), new Tag("population", "3748148")) }; ``` -------------------------------- ### Extract Powerlines to Shapefile - C# Source: https://github.com/osmsharp/core/blob/develop/samples/Sample.GeometryStream.Shape/README.md Use this code to extract powerline features from an OSM PBF file and save them as a shapefile. Ensure you filter data before converting to a feature stream to avoid excessive memory consumption. ```csharp using (var fileStream = File.OpenRead("path/to/file.osm.pbf")) { // create source stream. var source = new PBFOsmStreamSource(fileStream); // filter all powerlines and keep all nodes. var filtered = from osmGeo in source 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(); attributesTable.AddAttribute("type", "powerline"); foreach (var feature in lineStrings) { 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); } ``` -------------------------------- ### Filter OSM Data by Bounding Box Source: https://github.com/osmsharp/core/blob/develop/README.md Filter OSM data from a PBF file within a specified bounding box and write the filtered data to a new PBF file. The bounding box is defined by left, top, right, and bottom coordinates. ```csharp var source = new PBFOsmStreamSource( new FileInfo(@"/path/to/file.osm.pbf").OpenRead()); var filtered = source.FilterBox(6.238002777099609f, 49.72076145492323f, 6.272850036621093f, 49.69928180928878f); // left, top, right, bottom using (var stream = new FileInfo(@"/path/to/filterede.osm.pbf").Open(FileMode.Create, FileAccess.ReadWrite)) { var target = new PBFOsmStreamTarget(stream); target.RegisterSource(filtered); target.Pull(); } ``` -------------------------------- ### Filter OSM data using a bounding box Source: https://github.com/osmsharp/core/blob/develop/samples/Sample.GeoFilter/README.md Uses a bounding box defined by coordinates to filter nodes, ways, and relations from a PBF stream. ```csharp using (var fileStream = File.OpenRead("path/to/file.osm.pbf")) { // create source stream. var source = new PBFOsmStreamSource(fileStream); // filter by keeping everything inside the given polygon. var filtered = source.FilterBox(6.238002777099609f, 49.72076145492323f, 6.272850036621093f, 49.69928180928878f); ... } ``` -------------------------------- ### Extract Powerlines to GeoJSON Features Source: https://github.com/osmsharp/core/blob/develop/samples/Sample.GeometryStream/README.md Filters nodes and powerline ways from an OSM PBF file and converts them into a feature stream. Ensure filtering occurs before conversion to avoid excessive memory usage. ```csharp using (var fileStream = File.OpenRead("path/to/file.osm.pbf")) { // create source stream. var source = new PBFOsmStreamSource(fileStream); // filter all powerlines and keep all nodes. var filtered = from osmGeo in source 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; } ``` -------------------------------- ### Merge Multiple OSM Data Sources Source: https://context7.com/osmsharp/core/llms.txt The Merge extension method combines multiple OSM data sources into a single stream. Specify a ConflictResolutionType to handle overlapping data. The merged stream can then be written to a target. ```csharp using OsmSharp; using OsmSharp.Db; using OsmSharp.Streams; using System.IO; using var stream1 = File.OpenRead("region1.osm.pbf"); using var stream2 = File.OpenRead("region2.osm.pbf"); var source1 = new PBFOsmStreamSource(stream1); var source2 = new PBFOsmStreamSource(stream2); // Merge with conflict resolution (first stream wins) var merged = source1.Merge(ConflictResolutionType.FirstStream, source2); // Write merged data using var outputStream = File.Open("merged.osm.pbf", FileMode.Create); var target = new PBFOsmStreamTarget(outputStream); target.RegisterSource(merged); target.Pull(); ``` -------------------------------- ### Filter OSM data using LINQ Source: https://context7.com/osmsharp/core/llms.txt Leverages LINQ queries to filter OSM elements based on tags or types directly from the stream. ```csharp using OsmSharp; using OsmSharp.Streams; using System.IO; using System.Linq; using var fileStream = File.OpenRead("region.osm.pbf"); var source = new PBFOsmStreamSource(fileStream); // Filter using LINQ - find all restaurants var restaurants = from element in source where element.Type == OsmGeoType.Node && element.Tags != null && element.Tags.Contains("amenity", "restaurant") select element; foreach (var restaurant in restaurants) { var name = restaurant.Tags.GetValue("name") ?? "Unnamed"; var node = restaurant as Node; Console.WriteLine($"{name}: ({node.Latitude}, {node.Longitude})"); } ``` -------------------------------- ### Convert OSM to GeoJSON Features Source: https://context7.com/osmsharp/core/llms.txt Use the ToFeatureSource extension method to convert OSM objects to NetTopologySuite Feature objects for GeoJSON export. Filter elements before conversion and then filter the resulting features by geometry type. ```csharp using NetTopologySuite.Features; using NetTopologySuite.Geometries; using OsmSharp; using OsmSharp.Geo; using OsmSharp.Streams; using System.IO; using System.Linq; using var fileStream = File.OpenRead("region.osm.pbf"); var source = new PBFOsmStreamSource(fileStream); // Filter for power lines var filtered = from element in source where element.Type == OsmGeoType.Node || (element.Type == OsmGeoType.Way && element.Tags != null && element.Tags.Contains("power", "line")) select element; // Convert to features var features = filtered.ToFeatureSource(); // Filter for LineStrings and build collection var featureCollection = new FeatureCollection(); foreach (var feature in features.Where(f => f.Geometry is LineString)) { featureCollection.Add(feature); } // Serialize to GeoJSON var serializer = NetTopologySuite.IO.GeoJsonSerializer.Create(); using var writer = new StringWriter(); serializer.Serialize(writer, featureCollection); File.WriteAllText("powerlines.geojson", writer.ToString()); ``` -------------------------------- ### Filter OSM data by Bounding Box Source: https://context7.com/osmsharp/core/llms.txt Filters OSM elements within a specific geographic area defined by longitude and latitude coordinates. ```csharp using OsmSharp; using OsmSharp.Streams; using System.IO; // Extract data within Luxembourg City area using var sourceStream = File.OpenRead("europe.osm.pbf"); var source = new PBFOsmStreamSource(sourceStream); // Filter by bounding box: left, top, right, bottom (longitude/latitude) var filtered = source.FilterBox( 6.238002f, // left (min longitude) 49.720761f, // top (max latitude) 6.272850f, // right (max longitude) 49.699281f // bottom (min latitude) ); // Write filtered data to new file using var targetStream = File.Open("luxembourg-city.osm.pbf", FileMode.Create); var target = new PBFOsmStreamTarget(targetStream); target.RegisterSource(filtered); target.Pull(); ``` -------------------------------- ### Filter OSM data using a polygon Source: https://github.com/osmsharp/core/blob/develop/samples/Sample.GeoFilter/README.md Uses a defined polygon to filter spatial data from a PBF stream. ```csharp using (var fileStream = File.OpenRead("path/to/file.osm.pbf")) { // create source stream. var source = new PBFOsmStreamSource(fileStream); // filter by keeping everything inside the given polygon. var filtered = source.FilterSpatial(polygon); ... } ``` -------------------------------- ### Filter OSM data by Polygon Source: https://context7.com/osmsharp/core/llms.txt Uses the OsmSharp.Geo extension to filter OSM data based on an arbitrary polygon boundary. ```csharp using NetTopologySuite.Geometries; using OsmSharp.Geo; using OsmSharp.Streams; using System.IO; // Define a polygon boundary var coordinates = new[] { new Coordinate(6.10, 49.60), new Coordinate(6.30, 49.60), new Coordinate(6.30, 49.75), new Coordinate(6.10, 49.75), new Coordinate(6.10, 49.60) }; var polygon = new Polygon(new LinearRing(coordinates)); using var sourceStream = File.OpenRead("region.osm.pbf"); using var targetStream = File.Open("filtered.osm", FileMode.Create); var source = new PBFOsmStreamSource(sourceStream); var filtered = source.FilterSpatial(polygon, completeWays: true); var target = new XmlOsmStreamTarget(targetStream); target.RegisterSource(filtered); target.Pull(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.