public ShapefileDataReader(IStreamProviderRegistry streamProviderRegistry, IGeometryFactory geometryFactory) { if (streamProviderRegistry == null) { throw new ArgumentNullException("streamProviderRegistry"); } if (geometryFactory == null) { throw new ArgumentNullException("geometryFactory"); } _open = true; _dbfReader = new DbaseFileReader(streamProviderRegistry); _shpReader = new ShapefileReader(streamProviderRegistry, geometryFactory); _dbfHeader = _dbfReader.GetHeader(); _recordCount = _dbfHeader.NumRecords; // copy dbase fields to our own array. Insert into the first position, the shape column _dbaseFields = new DbaseFieldDescriptor[_dbfHeader.Fields.Length + 1]; _dbaseFields[0] = DbaseFieldDescriptor.ShapeField(); for (int i = 0; i < _dbfHeader.Fields.Length; i++) { _dbaseFields[i + 1] = _dbfHeader.Fields[i]; } _shpHeader = _shpReader.Header; _dbfEnumerator = _dbfReader.GetEnumerator(); _shpEnumerator = _shpReader.GetEnumerator(); _moreRecords = true; }
public List <Feature> LoadFeatureList(string filename) { List <Feature> features = new List <Feature>(); if (File.Exists(filename)) { using (ShapefileDataReader sdr = new ShapefileDataReader(filename, GeometryFactory.Default)) { DbaseFileHeader header = sdr.DbaseHeader; while (sdr.Read()) { Feature feature = new Feature(); AttributesTable attributesTable = new AttributesTable(); string[] keys = new string[header.NumFields]; Geometry geometry = (Geometry)sdr.Geometry; for (int i = 0; i < header.NumFields; i++) { DbaseFieldDescriptor fldDescriptor = header.Fields[i]; keys[i] = fldDescriptor.Name; attributesTable.AddAttribute(fldDescriptor.Name, sdr.GetValue(i)); } feature.Geometry = geometry; feature.Attributes = attributesTable; features.Add(feature); } } } return(features); }
/// <summary> /// Reads a shapefile into a arraylist of features that need converting from x,y coordinates to Long and Lat coordinates /// </summary> /// <param name="filename">name of the shapefile (the file that has all the polygons for the footpaths)</param> /// <param name="fact">the class that generates the structure of the points</param> /// <returns></returns> public ArrayList ReadSHP(string filename, GeometryFactory fact) { ArrayList features = new ArrayList(); //Array list for all the coordinates from the shapefile ShapefileDataReader sfDataReader = new ShapefileDataReader(filename, fact); //takes a file and a factory to build the geometries ShapefileHeader shpHeader = sfDataReader.ShapeHeader; //reads the headers of the file for checking and looping purposes DbaseFileHeader DHeader = sfDataReader.DbaseHeader; while (sfDataReader.Read() == true) //reading through all the data in the shapefile { Feature feature = new Feature(); //setting up a feature for each set of points AttributesTable atTable = new AttributesTable(); //table for the set of points string[] keys = new string[DHeader.NumFields]; Geometry geometry = sfDataReader.Geometry; for (int i = 0; i < DHeader.NumFields; i++) { DbaseFieldDescriptor fldDescriptor = DHeader.Fields[i]; keys[i] = fldDescriptor.Name; atTable.Add(fldDescriptor.Name, sfDataReader.GetValue(i)); } feature.Geometry = geometry; feature.Attributes = atTable; //setting the variables for the feature features.Add(feature); } sfDataReader.Close();//closing the reader sfDataReader.Dispose(); return(features); }
/// <summary> /// Reads a shapefile into a arraylist of features that need converting from x,y coordinates to Long and Lat coordinates /// </summary> /// <param name="filename">name of the shapefile (the file that has all the polygons for the footpaths)</param> /// <param name="fact">the class that generates the structure of the points</param> /// <returns></returns> public ArrayList ReadSHP(string filename, GeometryFactory fact) { ArrayList features = new ArrayList(); //Array list for all the coordinates from the shapefile ShapefileDataReader sfDataReader = new ShapefileDataReader(filename, fact); ShapefileHeader shpHeader = sfDataReader.ShapeHeader; DbaseFileHeader DHeader = sfDataReader.DbaseHeader; while (sfDataReader.Read() == true) { Feature feature = new Feature(); AttributesTable atTable = new AttributesTable(); string[] keys = new string[DHeader.NumFields]; Geometry geometry = sfDataReader.Geometry; for (int i = 0; i < DHeader.NumFields; i++) { DbaseFieldDescriptor fldDescriptor = DHeader.Fields[i]; keys[i] = fldDescriptor.Name; atTable.Add(fldDescriptor.Name, sfDataReader.GetValue(i)); } feature.Geometry = geometry; feature.Attributes = atTable; features.Add(feature); } sfDataReader.Close(); sfDataReader.Dispose(); return(features); }
/// <summary> /// Initializes a new instance of the ShapefileDataReader class. /// </summary> /// <param name="filename">The shapefile to read (minus the .shp extension)</param> ///<param name="geometryFactory">The GeometryFactory to use.</param> public ShapefileDataReader(string filename, IGeometryFactory geometryFactory) { if (String.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } if (geometryFactory == null) { throw new ArgumentNullException("geometryFactory"); } _open = true; string dbfFile = Path.ChangeExtension(filename, "dbf"); _dbfReader = new DbaseFileReader(dbfFile); string shpFile = Path.ChangeExtension(filename, "shp"); _shpReader = new ShapefileReader(shpFile, geometryFactory); _dbfHeader = _dbfReader.GetHeader(); _recordCount = _dbfHeader.NumRecords; // copy dbase fields to our own array. Insert into the first position, the shape column _dbaseFields = new DbaseFieldDescriptor[_dbfHeader.Fields.Length + 1]; _dbaseFields[0] = DbaseFieldDescriptor.ShapeField(); for (int i = 0; i < _dbfHeader.Fields.Length; i++) { _dbaseFields[i + 1] = _dbfHeader.Fields[i]; } _shpHeader = _shpReader.Header; _dbfEnumerator = _dbfReader.GetEnumerator(); _shpEnumerator = _shpReader.GetEnumerator(); _moreRecords = true; }
public static IReadOnlyCollection <Feature> ReadFeatures(this ShapefileDataReader shapefileDataReader) { List <Feature> features = new List <Feature>(); while (shapefileDataReader.Read()) { Feature feature = new Feature(); AttributesTable attributesTable = new AttributesTable(); DbaseFileHeader header = shapefileDataReader.DbaseHeader; 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); } return(features); }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType == typeof(Decimal)) { if (value == null || parameter == null) { return(null); } if (value is DbaseFieldDescriptor) { if (parameter is string) { DbaseFieldDescriptor descriptor = (DbaseFieldDescriptor)value; string param = ((string)parameter).ToLower(); if (param == "min") { return((decimal)((1 - Math.Pow(10, descriptor.Length - 1)) * Math.Pow(0.1, descriptor.DecimalCount))); } else if (param == "max") { return((decimal)((Math.Pow(10, descriptor.Length) - 1) * Math.Pow(0.1, descriptor.DecimalCount))); } } } } return(value); }
public JZD() { // --------------------- DbaseType ---------------------- // 字段类型 // C - 字符型 // Y - 货币型 // N - 数值型 // F - 浮点型 // D - 日期型 // T - 日期时间型 // B - 双精度型 // I - 整型 // L - 逻辑型 // M - 备注型 // G - 通用型 // C - 字符型(二进制) // M - 备注型(二进制) // P - 图片型 // ------------------------------------------------------- this.dbFields = new DbaseFieldDescriptor[2]; // 0 属性代码 - 字符串 6 dbFields[0] = new DbaseFieldDescriptor(); dbFields[0].Name = "属性代码"; dbFields[0].DbaseType = 'C'; dbFields[0].Length = 6; // 1 界址点号 - 字符串型 8 dbFields[1] = new DbaseFieldDescriptor(); dbFields[1].Name = "界址点号"; dbFields[1].DbaseType = 'C'; dbFields[1].Length = 8; }
public void LoadCountries(string path) { iso2Countries = new Dictionary <string, Feature>(); iso3Countries = new Dictionary <string, Feature>(); countryFeatures = new ArrayList(); countriesDt = new System.Data.DataTable(); GeometryFactory factory = new GeometryFactory(); using (ShapefileDataReader reader = new ShapefileDataReader(path, factory)) { foreach (var f in reader.DbaseHeader.Fields) { countriesDt.Columns.Add(f.Name, f.Type); } var keyCol = countryDtKeyCandidates .Intersect(countriesDt.Columns.OfType <System.Data.DataColumn>().Select(col => col.ColumnName)) .FirstOrDefault(); if (keyCol != null) { countriesDt.PrimaryKey = new System.Data.DataColumn[] { countriesDt.Columns[keyCol] }; } countriesDt.Columns.Add("WKT", typeof(string)); while (reader.Read()) { Feature feature = new Feature(); AttributesTable attributesTable = new AttributesTable(); string[] keys = new string[reader.DbaseHeader.NumFields]; IGeometry geometry = (Geometry)reader.Geometry; System.Data.DataRow row = countriesDt.NewRow(); for (int i = 0; i < reader.DbaseHeader.NumFields; i++) { DbaseFieldDescriptor fldDescriptor = reader.DbaseHeader.Fields[i]; keys[i] = fldDescriptor.Name; attributesTable.AddAttribute(fldDescriptor.Name, reader.GetValue(i)); row[i] = reader.GetValue(i); } row["WKT"] = geometry.AsText(); countriesDt.Rows.Add(row); feature.Geometry = geometry; feature.Attributes = attributesTable; if (feature.Attributes.Exists("ISO2") && feature.Attributes.Exists("ISO3")) { int index = countryFeatures.Add(feature); var iso2 = (string)feature.Attributes["ISO2"]; var iso3 = (string)feature.Attributes["ISO3"]; iso2Countries.Add(iso2, feature); iso3Countries.Add(iso3, feature); } } reader.Close(); } }
private void NewCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { Layer currentLayer; switch ((string)e.Parameter) { case "layer": NewLayerDialog newLayerDialog = new NewLayerDialog(); if (newLayerDialog.ShowDialog() == true) { Layer newLayer = new Layer(); DbaseFileReader reader = new DbaseFileReader( new NetTopologySuite.IO.Streams.ByteStreamProvider( NetTopologySuite.IO.Streams.StreamTypes.Data, new MemoryStream(Properties.Resources.EmptyDbaseHeader1))); newLayer.Header = reader.GetHeader(); newLayer.Name = newLayerDialog.LayerName; newLayer.ShapeType = newLayerDialog.ShapeType; Layers.Add(newLayer); } break; case "field": currentLayer = (Layer)CollectionViewSource.GetDefaultView(Layers).CurrentItem; currentLayer.Header.AddColumn(newFieldName.Text, ((string)((ComboBoxItem)newFieldType.SelectedItem).Tag)[0], newFieldLength.Value ?? 0, newFieldDecimals.Value ?? 0); DbaseFieldDescriptor descriptor = currentLayer.Header.Fields.Last(); currentLayer.Attributes.Add(descriptor); object newValue = null; var @switch = new Dictionary <Type, Action> { { typeof(Int32), () => newValue = 0 }, { typeof(Double), () => newValue = 0.0 }, { typeof(String), () => newValue = "" }, { typeof(DateTime), () => newValue = DateTime.UtcNow }, { typeof(Boolean), () => newValue = false }, }; @switch[descriptor.Type](); foreach (ShapefileShape shape in currentLayer.Shapes) { shape.Attributes.Add(new ShapefileAttributeEntry(descriptor, newValue)); } break; case "shape": currentLayer = (Layer)CollectionViewSource.GetDefaultView(Layers).CurrentItem; ShapefileShape newShape = new ShapefileShape(currentLayer.ShapeType); newShape.CreateAttributes(currentLayer.Attributes); currentLayer.Shapes.Add(newShape); break; default: break; } }
internal static IEnumerable <Feature> Load(string v) { var shapeFileDataReader = Shapefile.CreateDataReader(v, new GeometryFactory()); ShapefileHeader shpHeader = shapeFileDataReader.ShapeHeader; DbaseFileHeader header = shapeFileDataReader.DbaseHeader; shapeFileDataReader.Reset(); //Read through all records of the shapefile (geometry and attributes) into a feature collection List <Feature> features = new List <Feature>(); int j = 1; while (shapeFileDataReader.Read()) { Feature feature = new Feature(); AttributesTable attributesTable = new AttributesTable(); string[] keys = new string[header.NumFields]; var pm = new PrecisionModel(10.0); var pop = new NetTopologySuite.Precision.GeometryPrecisionReducer(pm); Geometry geometry = NetTopologySuite.Simplify.DouglasPeuckerSimplifier.Simplify(pop.Reduce((Geometry)shapeFileDataReader.Geometry), 0.5); // geometry = NetTopologySuite.Operation.BoundaryOp.GetBoundary(geometry); // var pol = new NetTopologySuite.Operation.Polygonize.Polygonizer(); // pol.Add() if (geometry.IsEmpty) { continue; } for (int i = 0; i < header.NumFields; i++) { DbaseFieldDescriptor fldDescriptor = header.Fields[i]; keys[i] = fldDescriptor.Name; attributesTable.Add(fldDescriptor.Name, shapeFileDataReader.GetValue(i + 1)); } if (!attributesTable.GetNames().Contains("NAME", StringComparer.InvariantCulture)) { attributesTable.Add("NAME", j); } feature.Geometry = geometry; feature.Attributes = attributesTable; features.Add(feature); j++; } //Close and free up any resources shapeFileDataReader.Close(); shapeFileDataReader.Dispose(); return(features); }
public void Get_Shape_Database_Properties() { var sut = _boroughBoundariesService.GetShapeDatabaseProperties(); Assert.NotNull(sut); //Display summary information about the Dbase file _testOutputHelper.WriteLine("Dbase info"); _testOutputHelper.WriteLine($"{sut.Fields.Length} Columns, {sut.NumRecords} Records"); for (int i = 0; i < sut.NumFields; i++) { DbaseFieldDescriptor fldDescriptor = sut.Fields[i]; _testOutputHelper.WriteLine($" {fldDescriptor.Name} {fldDescriptor.DbaseType}"); } }
/// <summary> /// /// </summary> /// <param name="columnValues"></param> public void Write(IList columnValues) { if (columnValues == null) throw new ArgumentNullException("columnValues"); if (!_headerWritten) throw new InvalidOperationException("Header records need to be written first."); int i = 0; _writer.Write((byte)0x20); // the deleted flag foreach (object columnValue in columnValues) { DbaseFieldDescriptor headerField = _header.Fields[i]; if (columnValue == null) // Don't corrupt the file by not writing if the value is null. // Instead, treat it like an empty string. Write(string.Empty, headerField.Length); else if (headerField.Type == typeof(string)) // If the column is a character column, the values in that // column should be treated as text, even if the column value // is not a string. Write(columnValue.ToString(), headerField.Length); else if (IsRealType(columnValue.GetType())) Write(Convert.ToDecimal(columnValue), headerField.Length, headerField.DecimalCount); else if (IsIntegerType(columnValue.GetType())) Write(Convert.ToDecimal(columnValue), headerField.Length, headerField.DecimalCount); else if (columnValue is Decimal) Write((decimal)columnValue, headerField.Length, headerField.DecimalCount); else if (columnValue is Boolean) Write((bool)columnValue); else if (columnValue is string) Write((string)columnValue, headerField.Length); else if (columnValue is DateTime) Write((DateTime)columnValue); else if (columnValue is Char) Write((Char)columnValue, headerField.Length); i++; } _writer.Flush(); //dbfStream.Seek(0, SeekOrigin.Begin); }
public static string GetSqlType(DbaseFieldDescriptor dbfType) { switch (dbfType.Type.Name) { case "Int64": return("[bigint]"); case "Byte[]": return("[varbinary](MAX)"); case "Boolean": return("[bit]"); case "DateTime": return("[datetime]"); case "DateTimeOffset": return("[DATETIMEOFFSET]"); case "Decimal": return("[decimal]"); case "Double": return("[float]"); case "Int32": return("[int]"); case "String": case "Char[]": return("[nvarchar](255)"); case "Single": return("[real]"); case "Int16": return("[smallint]"); case "Object": return("[sql_variant]"); case "TimeSpan": return("[time]"); case "Byte": return("[tinyint]"); case "Guid": return("[uniqueidentifier]"); case "byte": return("[varbinary](1)"); default: return("[nvarchar](MAX)"); } }
private void DeleteCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { Layer currentLayer; switch ((string)e.Parameter) { case "layer": if (MessageBox.Show("Are you sure you want to delete this layer?", "Delete Layer", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) { Layers.Remove((Layer)CollectionViewSource.GetDefaultView(Layers).CurrentItem); } break; case "field": currentLayer = (Layer)CollectionViewSource.GetDefaultView(Layers)?.CurrentItem; int currentIndex = CollectionViewSource.GetDefaultView(currentLayer.Attributes).CurrentPosition; DbaseFieldDescriptor descriptor = currentLayer.Attributes[currentIndex]; currentLayer.Header.RemoveColumn(descriptor.Name); currentLayer.Attributes.RemoveAt(currentIndex); foreach (ShapefileShape shape in currentLayer.Shapes) { shape.Attributes.RemoveAt(currentIndex); } break; case "shape": currentLayer = (Layer)CollectionViewSource.GetDefaultView(Layers)?.CurrentItem; var shapes = CollectionViewSource.GetDefaultView(currentLayer.Shapes); currentLayer.Shapes.Remove((ShapefileShape)shapes.CurrentItem); shapes.MoveCurrentTo(null); break; default: break; } }
public ShapefileAttributeEntry(DbaseFieldDescriptor dbaseFieldDescriptor, object value) { FieldDescriptor = dbaseFieldDescriptor; Value = value; }
//[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"]; } } }
public List <Object> CalculateDataTable(string polyfile) { //Calling EPA WATERS: //https://ofmpub.epa.gov/waters10/SpatialAssignment.Service?pGeometry=POINT(-76.7498+37.5)&pLayer=NHDPLUS_CATCHMENT&pAssignmentHint=9894716&pReturnGeometry=TRUE //List<GeoAPI.Geometries.IGeometry> polys = new List<GeoAPI.Geometries.IGeometry>(); List <GeoAPI.Geometries.IGeometry> squares = new List <GeoAPI.Geometries.IGeometry>(); ArrayList polys = new ArrayList(); ArrayList polyfeats = new ArrayList(); List <Object> infoTable = new List <Object>(); double squareArea = 0;//0.015625; double gridArea = 0; double polygonArea = 0; string catchmentID = ""; ////////////// string gridfile = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.shp";//""; string gridproj = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.prj"; ////////////// Guid gid = Guid.NewGuid(); string directory = @"M:\\TransientStorage\\" + gid.ToString() + "\\"; //This block is for getting and setting shapefiles for NLDAS Grid /** * client.DownloadFile("https://ldas.gsfc.nasa.gov/nldas/gis/NLDAS_Grid_Reference.zip", @"M:\\TransientStorage\\NLDAS.zip"); * ZipFile.ExtractToDirectory(@"M:\\TransientStorage\\NLDAS.zip", @"M:\\TransientStorage\\NLDAS"); * unzippedLocation = (@"M:\\TransientStorage\\NLDAS"); * foreach (string file in Directory.GetFiles(unzippedLocation)) * { * if (Path.GetExtension(file).Equals(".shp")) * { * gridfile = file; * } * else if (Path.GetExtension(file).Equals(".prj")) * { * gridproj = file; * } * } * client.Dispose();**/ ShapefileDataReader reader2 = new ShapefileDataReader(gridfile, NetTopologySuite.Geometries.GeometryFactory.Default); while (reader2.Read()) { squares.Add(reader2.Geometry); gridArea += reader2.Geometry.Area; } reader2.Dispose(); //if (polyfile.StartsWith(@"{""type"": ""FeatureCollection""")) if (polyfile.StartsWith(@"{""type"":"))//.geojson { Boolean version1 = true; string[] featureParams = new string[3]; string jsonfile = polyfile; var readera = new NetTopologySuite.IO.GeoJsonReader(); NetTopologySuite.Features.FeatureCollection result = readera.Read <NetTopologySuite.Features.FeatureCollection>(jsonfile); if (result[0].Attributes.GetNames().Contains("HUC_8")) { version1 = false; featureParams[0] = "OBJECTID"; featureParams[1] = "HUC_8"; featureParams[2] = "HUC_12"; } else if (result[0].Attributes.GetNames().Contains("HUC8")) { version1 = true; featureParams[0] = "COMID"; featureParams[1] = "HUC8"; featureParams[2] = "HUC12"; } else { version1 = false; featureParams[0] = null; featureParams[1] = null; featureParams[2] = null; } List <Object> huc8Table = new List <Object>(); Dictionary <string, string> h8 = new Dictionary <string, string>(); h8.Add("HUC 8 ID: ", result[0].Attributes[featureParams[1]].ToString()); huc8Table.Add(h8); //huc8Table.Add(new KeyValuePair<string, string>("HUC 8 ID: ", result[0].Attributes[featureParams[1]].ToString())); for (int i = 0; i < result.Count; i++) { List <Object> huc12Table = new List <Object>(); if (version1) { huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", null)); } else { Dictionary <string, string> h12 = new Dictionary <string, string>(); h12.Add("HUC 12 ID: ", result[i].Attributes["HUC_12"].ToString()); huc12Table.Add(h12); //huc12Table.Add(new KeyValuePair<string, string>("HUC 12 ID: ", result[i].Attributes["HUC_12"].ToString())); } catchmentID = result[i].Attributes[featureParams[0]].ToString(); Dictionary <string, string> cm = new Dictionary <string, string>(); cm.Add("Catchment ID: ", catchmentID); huc12Table.Add(cm); //huc12Table.Add(new KeyValuePair<string, string>("Catchment ID: ", catchmentID)); foreach (GeoAPI.Geometries.IGeometry s in squares) { double interArea = 0.0; squareArea = s.Area; if (result[i].Geometry.Intersects(s)) { GeoAPI.Geometries.IGeometry intersection = result[i].Geometry.Intersection(s); interArea += intersection.Area; double percent2 = (interArea / squareArea) * 100; Dictionary <string, string> catchTable = new Dictionary <string, string>(); //catchTable.Add("catchmentID", catchmentID); catchTable.Add("latitude", s.Centroid.X.ToString()); catchTable.Add("longitude", s.Centroid.Y.ToString()); catchTable.Add("cellArea", squareArea.ToString()); catchTable.Add("containedArea", interArea.ToString()); catchTable.Add("percentArea", percent2.ToString()); huc12Table.Add(catchTable); } } huc8Table.Add(huc12Table); } infoTable.Add(huc8Table); } else //Huc ID { catchmentID = polyfile; string ending = polyfile + ".zip"; WebClient client = new WebClient(); DirectoryInfo di = Directory.CreateDirectory(directory); client.DownloadFile("ftp://newftp.epa.gov/exposure/NHDV1/HUC12_Boundries/" + ending, directory + ending); string projfile = ""; string dataFile = ""; ZipFile.ExtractToDirectory(directory + ending, directory + polyfile); string unzippedLocation = (directory + polyfile + "\\" + polyfile); //+ "\\NHDPlus" + polyfile + "\\Drainage"); foreach (string file in Directory.GetFiles(unzippedLocation)) { if (Path.GetExtension(file).Equals(".shp")) { polyfile = file; } else if (Path.GetExtension(file).Equals(".prj")) { projfile = file; } else if (Path.GetExtension(file).Equals(".dbf")) { dataFile = file; } } //This block is for setting projection parameters of input shapefile and projecting it to NLDAS grid //Reprojecting of coordinates is not needed for NHDPlus V2 string line = System.IO.File.ReadAllText(projfile); //string line = @"PROJCS[""unnamed"",GEOGCS[""unnamed ellipse"",DATUM[""unknown"",SPHEROID[""unnamed"",6378137,0]],PRIMEM[""Greenwich"",0],UNIT[""degree"",0.0174532925199433]],PROJECTION[""Mercator_2SP""],PARAMETER[""latitude_of_origin"",0],PARAMETER[""standard_parallel_1"",0],PARAMETER[""central_meridian"",0],PARAMETER[""false_easting"",0],PARAMETER[""false_northing"",0],UNIT[""Meter"",1]]";//System.IO.File.ReadAllText(projfile); string[] projParams = { "PARAMETER", @"PARAMETER[""latitude_of_origin"",0]," };//@"PARAMETER[""false_easting"",0],", @"PARAMETER[""false_northing"",0],", @"PARAMETER[""central_meridian"",0],", @"PARAMETER[""standard_parallel_1"",0],", @"PARAMETER[""standard_parallel_2"",0],", @"PARAMETER[""latitude_Of_origin"",0]," }; int ptr = 0; foreach (string x in projParams) { if (line.Contains(x)) { ptr = line.IndexOf(x); } else if (!line.Contains(x) && !x.Equals("PARAMETER")) { line = line.Insert(ptr, x); } } string line2 = System.IO.File.ReadAllText(gridproj); IProjectedCoordinateSystem pcs = CoordinateSystemWktReader.Parse(line) as IProjectedCoordinateSystem; IGeographicCoordinateSystem gcs = GeographicCoordinateSystem.WGS84 as IGeographicCoordinateSystem; CoordinateTransformationFactory ctfac = new CoordinateTransformationFactory(); ICoordinateTransformation transformTo = ctfac.CreateFromCoordinateSystems(pcs, gcs); IMathTransform inverseTransformTo = transformTo.MathTransform; //Read geometries from both shapefiles and store in array lists ShapefileDataReader reader = new ShapefileDataReader(polyfile, NetTopologySuite.Geometries.GeometryFactory.Default); DbaseFileHeader header = reader.DbaseHeader; string huc8 = ""; while (reader.Read()) { //Reprojection not needed for NHDPLUSV2 CoordinateList cordlist = new CoordinateList(); foreach (Coordinate coord in reader.Geometry.Coordinates) { double[] newCoord = { coord.X, coord.Y }; newCoord = inverseTransformTo.Transform(newCoord); Coordinate newpt = new Coordinate(newCoord[0], newCoord[1]); cordlist.Add(newpt); } Coordinate[] listofpts = cordlist.ToCoordinateArray(); IGeometryFactory geoFactory = new NetTopologySuite.Geometries.GeometryFactory(); NetTopologySuite.Geometries.LinearRing linear = (NetTopologySuite.Geometries.LinearRing) new GeometryFactory().CreateLinearRing(listofpts); Feature feature = new Feature(); AttributesTable attributesTable = new AttributesTable(); string[] keys = new string[header.NumFields]; IGeometry geometry = (Geometry)reader.Geometry; for (int i = 0; i < header.NumFields; i++) { DbaseFieldDescriptor fldDescriptor = header.Fields[i]; keys[i] = fldDescriptor.Name; attributesTable.AddAttribute(fldDescriptor.Name, reader.GetValue(i)); } feature.Geometry = geometry; feature.Attributes = attributesTable; polyfeats.Add(feature.Attributes); huc8 = attributesTable.GetValues()[5].ToString(); Polygon projPoly = new Polygon(linear, null, geoFactory); polys.Add(projPoly); polygonArea += projPoly.Area; } reader.Dispose(); List <Object> huc8Table = new List <Object>(); Dictionary <string, string> h8 = new Dictionary <string, string>(); h8.Add("HUC 8 ID: ", catchmentID); huc8Table.Add(h8); int j = 0; foreach (Polygon p in polys) { List <Object> huc12Table = new List <Object>(); Dictionary <string, string> cm = new Dictionary <string, string>(); // AttributesTable tab = (AttributesTable)polyfeats[j]; object[] valuesl = tab.GetValues(); cm.Add("HUC 12 ID: ", valuesl[17].ToString()); huc12Table.Add(cm); //huc12Table.Add(new KeyValuePair<string, string>("HUC 12 ID: ", null)); catchmentID = null;//result[i].Attributes["OBJECTID"].ToString(); Dictionary <string, string> cm2 = new Dictionary <string, string>(); cm2.Add("Catchment ID: ", catchmentID); huc12Table.Add(cm2); //huc12Table.Add(new KeyValuePair<string, string>("Catchment ID: ", catchmentID)); foreach (GeoAPI.Geometries.IGeometry s in squares) { double interArea = 0.0; squareArea = s.Area; if (p.Intersects(s)) { GeoAPI.Geometries.IGeometry intersection = p.Intersection(s); interArea += intersection.Area; double percent2 = (interArea / squareArea) * 100; Dictionary <string, string> catchTable = new Dictionary <string, string>(); //catchTable.Add("catchmentID", catchmentID); catchTable.Add("latitude", s.Centroid.X.ToString()); catchTable.Add("longitude", s.Centroid.Y.ToString()); catchTable.Add("cellArea", squareArea.ToString()); catchTable.Add("containedArea", interArea.ToString()); catchTable.Add("percentArea", percent2.ToString()); huc12Table.Add(catchTable); } } huc8Table.Add(huc12Table); j++; } infoTable.Add(huc8Table); } //System.IO.DirectoryInfo del = new DirectoryInfo(directory); /* * foreach (FileInfo file in del.GetFiles()) * { * file.Delete(); * } * foreach (DirectoryInfo dir in del.GetDirectories()) * { * dir.Delete(true); * }*/ //del.Delete(true); return(infoTable); }