private void WriteZippedShapefile(ZipOutputStream zipStream, DataTable table, string baseName) { ShapeFileWriter writer = new ShapeFileWriter(table); MemoryStream memStream = new MemoryStream(); writer.WriteShp(memStream); byte[] buffer = memStream.ToArray(); ZipEntry entry = new ZipEntry(baseName + ".shp"); entry.Size = buffer.Length; zipStream.PutNextEntry(entry); zipStream.Write(buffer, 0, buffer.Length); memStream = new MemoryStream(); writer.WriteShx(memStream); buffer = memStream.ToArray(); entry = new ZipEntry(baseName + ".shx"); entry.Size = buffer.Length; zipStream.PutNextEntry(entry); zipStream.Write(buffer, 0, buffer.Length); memStream = new MemoryStream(); writer.WriteDbf(memStream); buffer = memStream.ToArray(); entry = new ZipEntry(baseName + ".dbf"); entry.Size = buffer.Length; zipStream.PutNextEntry(entry); zipStream.Write(buffer, 0, buffer.Length); }
public void SaveAsShpFile(String fileName, double offsetLat = 0, double offsetLng = 0) { //写入文件 String rootDir = Path.GetDirectoryName(fileName); String shapeFileName = Path.GetFileNameWithoutExtension(fileName); ShapeType shapeType = ShapeType.PolyLine; DbfFieldDesc[] fields = new DbfFieldDesc[] { new DbfFieldDesc { FieldName = "ID", FieldType = DbfFieldType.Character, FieldLength = 14, RecordOffset = 0 }, //new DbfFieldDesc { FieldName = "Name", FieldType = DbfFieldType.Character, FieldLength = 18, RecordOffset = 14 }, }; ShapeFileWriter sfw = ShapeFileWriter.CreateWriter(rootDir, shapeFileName, shapeType, fields); foreach (Edge e in Edges.Values) { String id = e.ID.ToString(); if (e.ID % 2 == 0) { continue; } String[] fieldData = new string[] { id }; List <PointF> vertices = new List <PointF>(); for (int i = 0; i < e.Geo.Points.Count; i++) { float lng = (float)(e.Geo.Points[i].Lng + offsetLng); float lat = (float)(e.Geo.Points[i].Lat + offsetLat); vertices.Add(new PointF(lng, lat)); } sfw.AddRecord(vertices.ToArray(), vertices.Count, fieldData); } sfw.Close(); }
public static void GenerateParkingRegionShape(List <MBR> mbrs, string fileName, bool addDev = false) { String rootDir = Path.GetDirectoryName(fileName); String shapeFileName = Path.GetFileNameWithoutExtension(fileName); var transform = new Wgs2MgsTransform(); // Read txt ShapeType shapeType = ShapeType.PolyLine; DbfFieldDesc[] shpFields = new DbfFieldDesc[] { new DbfFieldDesc { FieldName = "ID", FieldType = DbfFieldType.Character, FieldLength = 14, RecordOffset = 0 }, //new DbfFieldDesc { FieldName = "Name", FieldType = DbfFieldType.Character, FieldLength = 18, RecordOffset = 14 }, }; ShapeFileWriter sfw = ShapeFileWriter.CreateWriter(rootDir, shapeFileName, shapeType, shpFields); foreach (var mbr in mbrs) { String[] fieldData = new string[] { " " }; List <PointF> vertices = new List <PointF>(); GeoPoint[] points = new GeoPoint[] { mbr.TopLeft, mbr.TopRight, mbr.BottomRight, mbr.BottomLeft, mbr.TopLeft }; for (int i = 0; i < points.Length; ++i) { var point = points[i]; if (addDev) { point = transform.Transform(point); } vertices.Add(point.ToPointF()); } sfw.AddRecord(vertices.ToArray(), vertices.Count, fieldData); } sfw.Close(); }
private static void setParkingPointsAsShapeFile(List <GeoPoint> points, string fileName, bool addDev = false) { //写入文件 String rootDir = Path.GetDirectoryName(fileName); String shapeFileName = Path.GetFileNameWithoutExtension(fileName); ShapeType shapeType = ShapeType.Point; var transform = new Wgs2MgsTransform(); DbfFieldDesc[] fields = new DbfFieldDesc[] { new DbfFieldDesc { FieldName = "ID", FieldType = DbfFieldType.Character, FieldLength = 14, RecordOffset = 0 }, //new DbfFieldDesc { FieldName = "Name", FieldType = DbfFieldType.Character, FieldLength = 18, RecordOffset = 14 }, }; ShapeFileWriter sfw = ShapeFileWriter.CreateWriter(rootDir, shapeFileName, shapeType, fields); foreach (var p in points) { String[] fieldData = new string[] { " " }; List <PointF> vertices = new List <PointF>(); GeoPoint point = p; if (addDev) { point = transform.Transform(point); } float lng = (float)(point.Lng); float lat = (float)(point.Lat); vertices.Add(new PointF(lng, lat)); sfw.AddRecord(vertices.ToArray(), vertices.Count, fieldData); } sfw.Close(); }
public void Export(string folder, string name) { if (_layer.Features.Count == 0) { return; } using (var writer = ShapeFileWriter.CreateWriter(folder, name, GetShapeType(), GetFields())) { foreach (var feature in _layer.Features) { writer.AddRecord(GetPoints(feature), feature.GeoData.Count, GetFields(feature)); } } }
private static void setAsShapeFile(Dictionary <long, HashSet <string> > edgeDevicesDict, Graph graph, string fileName, bool addDev = false) { //写入文件 String rootDir = Path.GetDirectoryName(fileName); String shapeFileName = Path.GetFileNameWithoutExtension(fileName); ShapeType shapeType = ShapeType.PolyLine; var transform = new Wgs2MgsTransform(); int threshold = 1; DbfFieldDesc[] fields = new DbfFieldDesc[] { new DbfFieldDesc { FieldName = "ID", FieldType = DbfFieldType.Character, FieldLength = 14, RecordOffset = 0 }, //new DbfFieldDesc { FieldName = "Name", FieldType = DbfFieldType.Character, FieldLength = 18, RecordOffset = 14 }, }; ShapeFileWriter sfw = ShapeFileWriter.CreateWriter(rootDir, shapeFileName, shapeType, fields); foreach (var p in edgeDevicesDict) //foreach (Edge e in Edges.Values) { if (edgeDevicesDict.Count < threshold) { continue; } Edge e = graph.Edges[p.Key]; String id = e.ID.ToString(); if (e.ID % 2 == 0) { continue; } String[] fieldData = new string[] { "" }; List <PointF> vertices = new List <PointF>(); for (int i = 0; i < e.Geo.Points.Count; i++) { GeoPoint point = e.Geo.Points[i]; if (addDev) { point = transform.Transform(point); } float lng = (float)(point.Lng); float lat = (float)(point.Lat); vertices.Add(new PointF(lng, lat)); } sfw.AddRecord(vertices.ToArray(), vertices.Count, fieldData); } sfw.Close(); }
public static void GenerateParkingRegionShapeFromFile(string fileName, bool addDev = false) { string txtFileName = Path.Combine(Constants.DATA_DIR, "beijingTrjPart", "stat", "parkingRegion.txt"); //string fileName = Path.Combine(Constants.DATA_DIR, "beijingTrjPart", "shp", "parkingRegion.shp"); String rootDir = Path.GetDirectoryName(fileName); String shapeFileName = Path.GetFileNameWithoutExtension(fileName); var transform = new Wgs2MgsTransform(); // Read txt string[] lines = File.ReadAllLines(txtFileName); ShapeType shapeType = ShapeType.PolyLine; DbfFieldDesc[] shpFields = new DbfFieldDesc[] { new DbfFieldDesc { FieldName = "ID", FieldType = DbfFieldType.Character, FieldLength = 14, RecordOffset = 0 }, //new DbfFieldDesc { FieldName = "Name", FieldType = DbfFieldType.Character, FieldLength = 18, RecordOffset = 14 }, }; ShapeFileWriter sfw = ShapeFileWriter.CreateWriter(rootDir, shapeFileName, shapeType, shpFields); foreach (var line in lines) { var fields = line.Split(new char[] { ',' }); if (fields.Length % 2 != 0) { continue; } String[] fieldData = new string[] { " " }; List <PointF> vertices = new List <PointF>(); for (int i = 0; i < fields.Length; i += 2) { float lat = float.Parse(fields[i]); float lng = float.Parse(fields[i + 1]); GeoPoint point = new GeoPoint(lat, lng); if (addDev) { point = transform.Transform(point); } vertices.Add(new PointF((float)point.Lng, (float)point.Lat)); } sfw.AddRecord(vertices.ToArray(), vertices.Count, fieldData); } sfw.Close(); }
private void WriteZippedShapefile(ZipOutputStream zipStream, DataTable table, string baseName) { ShapeFileWriter writer = new ShapeFileWriter(table); MemoryStream memStream = new MemoryStream(); writer.WriteShp(memStream); byte[] buffer = memStream.ToArray(); ZipEntry entry = new ZipEntry(baseName + ".shp"); entry.Size = buffer.Length; zipStream.PutNextEntry(entry); zipStream.Write(buffer, 0, buffer.Length); memStream = new MemoryStream(); writer.WriteShx(memStream); buffer = memStream.ToArray(); entry = new ZipEntry(baseName + ".shx"); entry.Size = buffer.Length; zipStream.PutNextEntry(entry); zipStream.Write(buffer, 0, buffer.Length); memStream = new MemoryStream(); writer.WriteDbf(memStream); buffer = memStream.ToArray(); entry = new ZipEntry(baseName + ".dbf"); entry.Size = buffer.Length; zipStream.PutNextEntry(entry); zipStream.Write(buffer, 0, buffer.Length); }
/// <summary> /// Genera la salida en SHP /// </summary> private void generaSHPSalida() { try { final = 0; if (items.Count > 0) { if (String.IsNullOrEmpty(pathFile)) { pathFile = txtCarpetaSalida.Text; } if (String.IsNullOrEmpty(nameFile)) { var frmNombre = new FrmNombre(); frmNombre.ShowDialog(); nameFile = frmNombre.Texto; } string archivoSalidaDatos = ""; String nombreFichero = Path.GetFileNameWithoutExtension(String.Format("{0}\\{1}", pathFile, nameFile)); archivoSalidaDatos = String.Format("{0}\\{1}_salida.dat", pathFile, nombreFichero); var fs = new FileStream(archivoSalidaDatos, FileMode.Create); var sw = new StreamWriter(fs); if (checkCovariables.Checked) { sw.Write("{0}{1}{2}{3}{4}{5}{6}{7}{8}", "Toponimo", separador, "Latitud", separador, "Longitud", separador, "X", separador, "Y"); foreach (var cov in covariables) { sw.Write("{0}{1}", separador, cov.Nombre); } sw.Write("\n"); } else { sw.WriteLine("{0}{1}{2}{3}{4}{5}{6}{7}{8}", "Toponimo", separador, "Latitud", separador, "Longitud", separador, "X", separador, "Y"); } DbfFieldDesc[] camposdb = null; int numDatos = 2; ShapeFileWriter shapefilewrite = null; if (checkCovariables.Checked) { int numCovariables = covariables.Count; numDatos = numCovariables + 2; camposdb = new DbfFieldDesc[numCovariables + 2]; camposdb[0].FieldType = DbfFieldType.Character; camposdb[0].FieldLength = 50; camposdb[0].FieldName = "ObjectId"; camposdb[1].FieldType = DbfFieldType.Character; camposdb[1].FieldLength = 255; camposdb[1].FieldName = "Toponimo"; for (int i = 0; i < numCovariables; i++) { camposdb[i + 2].FieldName = covariables[i].Nombre; switch (covariables[i].Tipo) { case TiposDatos.CADENA: camposdb[i + 2].FieldType = DbfFieldType.Character; camposdb[i + 2].FieldLength = 255; break; case TiposDatos.DECIMAL: camposdb[i + 2].FieldType = DbfFieldType.FloatingPoint; camposdb[i + 2].FieldLength = 19; camposdb[i + 2].DecimalCount = 8; break; case TiposDatos.ENTERO: camposdb[i + 2].FieldType = DbfFieldType.Number; camposdb[i + 2].FieldLength = 15; break; case TiposDatos.FECHA: camposdb[i + 2].FieldType = DbfFieldType.Date; camposdb[i + 2].FieldLength = 8; break; } } } else { camposdb = new DbfFieldDesc[2]; camposdb[0].FieldType = DbfFieldType.Character; camposdb[0].FieldLength = 50; camposdb[0].FieldName = "ObjectId"; camposdb[1].FieldType = DbfFieldType.Character; camposdb[1].FieldLength = 255; camposdb[1].FieldName = "Toponimo"; } shapefilewrite = ShapeFileWriter.CreateWriter(pathFile, nombreFichero, ShapeType.Point, camposdb); foreach (var kv in items) { try { RegistroModel rm = listadoRegistro.FirstOrDefault(obj => String.Equals(obj.Id, kv.Value.key, StringComparison.InvariantCultureIgnoreCase)); string[] datos = new string[numDatos]; datos[0] = kv.Value.key; datos[1] = kv.Value.Direccion; sw.Write("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}", kv.Value.Direccion, separador, kv.Value.Latitud.ToString("##########.########", CultureInfo.InvariantCulture), separador, kv.Value.Longitud.ToString("##########.########", CultureInfo.InvariantCulture), separador, kv.Value.X.ToString("##########.##", CultureInfo.InvariantCulture), separador, kv.Value.Y.ToString("##########.##", CultureInfo.InvariantCulture), separador); if (checkCovariables.Checked) { for (int i = 0; i < covariables.Count; i++) { if (rm == null) { continue; } if (rm.Covariables[i] is DateTime) { var fecha = (DateTime)rm.Covariables[i]; datos[i + 2] = fecha.ToString("yyyyMMdd"); if (i == covariables.Count - 1) { sw.Write("{0}", fecha.ToShortDateString()); } else { sw.Write("{0}{1}", fecha.ToShortDateString(), separador); } } else if (rm.Covariables[i] is Double) { var doble = (Double)rm.Covariables[i]; datos[i + 2] = doble.ToString("##########.########", CultureInfo.InvariantCulture); if (i == covariables.Count - 1) { sw.Write("{0}", doble.ToString("##########.########", CultureInfo.InvariantCulture)); } else { sw.Write("{0}{1}", doble.ToString("##########.########", CultureInfo.InvariantCulture), separador); } } else { datos[i + 2] = rm.Covariables[i].ToString(); } } } sw.Write("\n"); if (!double.IsNaN(kv.Value.X) && !double.IsNaN(kv.Value.Y)) { if (shapefilewrite != null) { shapefilewrite.AddRecord( new[] { kv.Value.X, kv.Value.Y }, 1, datos); } } } catch (Exception ex) { final = 1; } }//Fin foreach de items georreferenciados if (shapefilewrite != null) { shapefilewrite.Close(); } sw.Flush(); sw.Close(); StreamWriter spjr = new StreamWriter(String.Format("{0}\\{1}.prj", pathFile, nombreFichero)); spjr.Write(Settings.Default.Proyeccion); spjr.Close(); StreamWriter scfg = new StreamWriter(String.Format("{0}\\{1}.cfg", pathFile, nombreFichero)); scfg.Write("UTF-8"); scfg.Close(); } else { MessageBox.Show(Resources.No_Existen_Registros, Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (Exception ex) { final = -1; BeginInvoke(new DlgMensaje(escribeConsolaRojo), new object[] { ex.Message }); } }
/// <summary> /// Converts a CSV file into a point shapefile /// </summary> /// <param name="csvPath"></param> /// <param name="shapefilePath"></param> /// <param name="xCoordFieldName"></param> /// <param name="yCoordFieldName"></param> /// <param name="matchFieldsExact"></param> /// <param name="progressHandler"></param> /// <param name="trimQuotesFromValues"></param> /// <remarks> /// CSV data must contain fields with point coordinates /// </remarks> public static void ConvertCsvToShapeFile(string csvPath, string shapefilePath, string xCoordFieldName, string yCoordFieldName, bool matchFieldsExact = true, ConvertShapeFileProgress progressHandler = null, bool trimQuotesFromValues = true) { string[] fieldNames = CsvUtil.ReadFieldHeaders(csvPath); CsvUtil.TrimValues(fieldNames); CsvUtil.TrimValues(fieldNames, new char[] { '"', '\'' }); int yCoordIndex = -1, xCoordIndex = -1; for (int n = 0; n < fieldNames.Length; ++n) { if (matchFieldsExact) { if (yCoordIndex < 0 && fieldNames[n].Equals(yCoordFieldName, StringComparison.OrdinalIgnoreCase)) { yCoordIndex = n; } } else { if (yCoordIndex < 0 && fieldNames[n].IndexOf(yCoordFieldName, StringComparison.OrdinalIgnoreCase) >= 0) { yCoordIndex = n; } } if (matchFieldsExact) { if (xCoordIndex < 0 && fieldNames[n].Equals(xCoordFieldName, StringComparison.OrdinalIgnoreCase)) { xCoordIndex = n; } } else { if (xCoordIndex < 0 && fieldNames[n].IndexOf(xCoordFieldName, StringComparison.OrdinalIgnoreCase) >= 0) { xCoordIndex = n; } } } if (yCoordIndex < 0 || xCoordIndex < 0) { throw new Exception(string.Format("Could not find '{0}' or '{1}' field", xCoordFieldName, yCoordFieldName)); } //ensure no duplicate field names after trimming to 10 characters string[] dbfFieldNames = GetDbfFieldNames(fieldNames); DbfFieldDesc[] fields = new DbfFieldDesc[fieldNames.Length]; for (int n = 0; n < fieldNames.Length; ++n) { fields[n].FieldName = dbfFieldNames[n]; fields[n].FieldLength = 1; fields[n].FieldType = DbfFieldType.Character; } int totalRecords = 0; using (System.IO.StreamReader reader = new StreamReader(new FileStream(csvPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { //skip header string nextLine = reader.ReadLine(); while ((nextLine = reader.ReadLine()) != null) { string[] values = nextLine.Split(','); if (values.Length != fieldNames.Length) { continue; } CsvUtil.TrimValues(values); CsvUtil.TrimValues(values, new char[] { '"', '\'' }); for (int n = values.Length - 1; n >= 0; --n) { fields[n].FieldLength = Math.Max(fields[n].FieldLength, values[n].Length); } totalRecords++; } } using (ShapeFileWriter writer = ShapeFileWriter.CreateWriter(System.IO.Path.GetDirectoryName(shapefilePath), System.IO.Path.GetFileNameWithoutExtension(shapefilePath), ShapeType.Point, fields)) { using (System.IO.StreamReader reader = new StreamReader(new FileStream(csvPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { double[] pts = new double[2]; //skip header string nextLine = reader.ReadLine(); int progress = 0; int count = 0; while ((nextLine = reader.ReadLine()) != null) { string[] values = nextLine.Split(','); CsvUtil.TrimValues(values); if (trimQuotesFromValues) { CsvUtil.TrimValues(values, new char[] { '"', '\'' }); } string yString = values[yCoordIndex]; if (yString.Length > 0) { //trim any quotes yString = yString.Trim('"', '\''); } string xString = values[xCoordIndex]; if (xString.Length > 0) { //trim any quotes xString = xString.Trim('"', '\''); } if (!double.TryParse(yString, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out pts[1])) { continue; } if (!double.TryParse(xString, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out pts[0])) { continue; } if (Math.Abs(pts[0] - -100000000) < 0.000001 || Math.Abs(pts[1] - -100000000) < 0.000001) { continue; } writer.AddRecord(pts, 1, values); ++count; if (progressHandler != null && (totalRecords > 0)) { int currentProgress = (int)Math.Round(100.0 * (double)count / totalRecords); if (currentProgress != progress) { progressHandler(new ConvertShapeFileEventArgs() { ProgressPercent = currentProgress }); progress = currentProgress; } } } } } if (progressHandler != null) { progressHandler(new ConvertShapeFileEventArgs() { ProgressPercent = 100 }); } }
public void exportshapefilesmethod( string exportDir, string shapeBaseName, string polylineSuffix, string blockSuffix, Database database = null) { DocumentCollection docCol = Application.DocumentManager; Database localDb = database ?? docCol.MdiActiveDocument.Database; Document doc = docCol.MdiActiveDocument; using (Transaction tx = localDb.TransactionManager.StartTransaction()) { try { Log.log($"Exporting to {exportDir}."); #region Exporting (p)lines HashSet <Polyline> pls = localDb.HashSetOfType <Polyline>(tx); pls = pls.Where(pl => (pl.Layer.Contains("FJV-TWIN") || pl.Layer.Contains("FJV-FREM") || pl.Layer.Contains("FJV-RETUR"))) .Where(pl => GetPipeDN(pl) != 999) .ToHashSet(); Log.log($"{pls.Count} polyline(s) found for export."); #region Field def DbfFieldDesc[] dbfFields = new DbfFieldDesc[3]; dbfFields[0].FieldName = "DN"; dbfFields[0].FieldType = DbfFieldType.Character; dbfFields[0].FieldLength = 10; dbfFields[1].FieldName = "System"; dbfFields[1].FieldType = DbfFieldType.Character; dbfFields[1].FieldLength = 100; dbfFields[2].FieldName = "Serie"; dbfFields[2].FieldType = DbfFieldType.Character; dbfFields[2].FieldLength = 100; #endregion using (ShapeFileWriter writer = ShapeFileWriter.CreateWriter( exportDir, shapeBaseName + polylineSuffix, ShapeType.PolyLine, dbfFields, EGIS.Projections.CoordinateReferenceSystemFactory.Default.GetCRSById(25832) .GetWKT(EGIS.Projections.PJ_WKT_TYPE.PJ_WKT1_GDAL, false))) { foreach (Polyline pline in pls) { List <Point2d> points = new List <Point2d>(); int numOfVert = pline.NumberOfVertices - 1; if (pline.Closed) { numOfVert++; } for (int i = 0; i < numOfVert; i++) { switch (pline.GetSegmentType(i)) { case SegmentType.Line: LineSegment2d ls = pline.GetLineSegment2dAt(i); if (i == 0) { //First iteration points.Add(ls.StartPoint); } points.Add(ls.EndPoint); break; case SegmentType.Arc: CircularArc2d arc = pline.GetArcSegment2dAt(i); double sPar = arc.GetParameterOf(arc.StartPoint); double ePar = arc.GetParameterOf(arc.EndPoint); double length = arc.GetLength(sPar, ePar); double radians = length / arc.Radius; int nrOfSamples = (int)(radians / 0.04); if (nrOfSamples < 3) { if (i == 0) { points.Add(arc.StartPoint); } points.Add(arc.EndPoint); } else { Point2d[] samples = arc.GetSamplePoints(nrOfSamples); if (i != 0) { samples = samples.Skip(1).ToArray(); } foreach (Point2d p2d in samples) { points.Add(p2d); } } break; case SegmentType.Coincident: case SegmentType.Point: case SegmentType.Empty: default: continue; } } PointD[] shapePoints = points.Select(p => new PointD(p.X, p.Y)).ToArray(); string[] attributes = new string[3]; attributes[0] = GetPipeDN(pline).ToString(); attributes[1] = GetPipeType(pline).ToString(); attributes[2] = GetPipeSeries(pline); writer.AddRecord(shapePoints, shapePoints.Length, attributes); } } #endregion #region Exporting BRs System.Data.DataTable komponenter = CsvReader.ReadCsvToDataTable( @"X:\AutoCAD DRI - 01 Civil 3D\FJV Dynamiske Komponenter.csv", "FjvKomponenter"); HashSet <BlockReference> allBrs = localDb.HashSetOfType <BlockReference>(tx); HashSet <BlockReference> brs = allBrs.Where(x => UtilsDataTables.ReadStringParameterFromDataTable( x.RealName(), komponenter, "Navn", 0) != default).ToHashSet(); Log.log($"{brs.Count} br(s) found for export."); //Handle legacy blocks System.Data.DataTable stdBlocks = CsvReader.ReadCsvToDataTable(@"X:\AutoCAD DRI - 01 Civil 3D\FJV Komponenter.csv", "FjvKomponenter"); HashSet <BlockReference> legacyBrs = allBrs.Where(x => UtilsDataTables.ReadStringParameterFromDataTable( x.Name, stdBlocks, "Navn", 0) != default).ToHashSet(); if (brs.Count > 0) { Log.log($"Legacy blocks detected: {legacyBrs.Count}."); } #region Field def dbfFields = new DbfFieldDesc[8]; dbfFields[0].FieldName = "BlockName"; dbfFields[0].FieldType = DbfFieldType.Character; dbfFields[0].FieldLength = 100; dbfFields[1].FieldName = "Type"; dbfFields[1].FieldType = DbfFieldType.Character; dbfFields[1].FieldLength = 100; dbfFields[2].FieldName = "Rotation"; dbfFields[2].FieldType = DbfFieldType.Character; dbfFields[2].FieldLength = 100; dbfFields[3].FieldName = "System"; dbfFields[3].FieldType = DbfFieldType.Character; dbfFields[3].FieldLength = 100; dbfFields[4].FieldName = "DN1"; dbfFields[4].FieldType = DbfFieldType.Character; dbfFields[4].FieldLength = 100; dbfFields[5].FieldName = "DN2"; dbfFields[5].FieldType = DbfFieldType.Character; dbfFields[5].FieldLength = 100; dbfFields[6].FieldName = "Serie"; dbfFields[6].FieldType = DbfFieldType.Character; dbfFields[6].FieldLength = 100; dbfFields[7].FieldName = "Vinkel"; dbfFields[7].FieldType = DbfFieldType.Character; dbfFields[7].FieldLength = 100; #endregion using (ShapeFileWriter writer = ShapeFileWriter.CreateWriter( exportDir, shapeBaseName + blockSuffix, ShapeType.Point, dbfFields, EGIS.Projections.CoordinateReferenceSystemFactory.Default.GetCRSById(25832) .GetWKT(EGIS.Projections.PJ_WKT_TYPE.PJ_WKT1_GDAL, false))) { foreach (BlockReference br in brs) { PointD[] shapePoints = new PointD[1]; shapePoints[0] = new PointD(br.Position.X, br.Position.Y); string[] attributes = new string[8]; attributes[0] = br.RealName(); attributes[1] = ReadComponentType(br, komponenter); attributes[2] = ReadBlockRotation(br, komponenter).ToString("0.00"); attributes[3] = ReadComponentSystem(br, komponenter); attributes[4] = ReadComponentDN1(br, komponenter); attributes[5] = ReadComponentDN2(br, komponenter); attributes[6] = ReadComponentSeries(br, komponenter); attributes[7] = ReadComponentVinkel(br, komponenter); writer.AddRecord(shapePoints, shapePoints.Length, attributes); } foreach (BlockReference br in legacyBrs) { PointD[] shapePoints = new PointD[1]; shapePoints[0] = new PointD(br.Position.X, br.Position.Y); string[] attributes = new string[8]; attributes[0] = br.Name; attributes[1] = ReadStringParameterFromDataTable(br.Name, stdBlocks, "Type", 0); attributes[2] = (br.Rotation * (180 / Math.PI)).ToString("0.##"); attributes[3] = ReadStringParameterFromDataTable(br.Name, stdBlocks, "System", 0); attributes[4] = ReadStringParameterFromDataTable(br.Name, stdBlocks, "DN1", 0);; attributes[5] = ReadStringParameterFromDataTable(br.Name, stdBlocks, "DN2", 0);; attributes[6] = "S3"; attributes[7] = "0"; writer.AddRecord(shapePoints, shapePoints.Length, attributes); } } #endregion } catch (System.Exception ex) { tx.Abort(); Log.log($"EXCEPTION!!!: {ex.ToString()}. Aborting export of current file!"); throw new System.Exception(ex.ToString()); //return; } tx.Abort(); } }
public void exportareas() { DocumentCollection docCol = Application.DocumentManager; Database localDb = docCol.MdiActiveDocument.Database; Document doc = docCol.MdiActiveDocument; using (Transaction tx = localDb.TransactionManager.StartTransaction()) { string logFileName = @"X:\AutoCAD DRI - QGIS\EGIS\Export\export.log"; Log.LogFileName = logFileName; PropertySetManager psm = new PropertySetManager(localDb, PSetDefs.DefinedSets.DriOmråder); PSetDefs.DriOmråder driOmråder = new PSetDefs.DriOmråder(); try { string fileName = localDb.OriginalFileName; string baseDir = @"X:\037-1178 - Gladsaxe udbygning - Dokumenter\01 Intern\04 Projektering\05 Optælling til TBL\"; string shapeName = "Områder"; Log.log($"Exporting to {baseDir}."); #region Exporting (p)lines HashSet <Polyline> pls = localDb.HashSetOfType <Polyline>(tx); pls = pls.Where(pl => pl.Layer == "0-OMRÅDER-OK").ToHashSet(); Log.log($"{pls.Count} object(s) found for export."); DbfFieldDesc[] dbfFields = new DbfFieldDesc[4]; dbfFields[0].FieldName = "Vejnavn"; dbfFields[0].FieldType = DbfFieldType.General; dbfFields[0].FieldLength = 100; dbfFields[1].FieldName = "Vejklasse"; dbfFields[1].FieldType = DbfFieldType.Number; dbfFields[1].FieldLength = 10; dbfFields[2].FieldName = "Belaegning"; dbfFields[2].FieldType = DbfFieldType.General; dbfFields[2].FieldLength = 100; dbfFields[3].FieldName = "Nummer"; dbfFields[3].FieldType = DbfFieldType.General; dbfFields[3].FieldLength = 100; using (ShapeFileWriter writer = ShapeFileWriter.CreateWriter( baseDir, shapeName, ShapeType.PolyLine, dbfFields, EGIS.Projections.CoordinateReferenceSystemFactory.Default.GetCRSById(25832) .GetWKT(EGIS.Projections.PJ_WKT_TYPE.PJ_WKT1_GDAL, false))) { foreach (Polyline pline in pls) { List <Point2d> points = new List <Point2d>(); int numOfVert = pline.NumberOfVertices - 1; if (pline.Closed) { numOfVert++; } for (int i = 0; i < numOfVert; i++) { switch (pline.GetSegmentType(i)) { case SegmentType.Line: LineSegment2d ls = pline.GetLineSegment2dAt(i); if (i == 0) { //First iteration points.Add(ls.StartPoint); } points.Add(ls.EndPoint); break; case SegmentType.Arc: CircularArc2d arc = pline.GetArcSegment2dAt(i); double sPar = arc.GetParameterOf(arc.StartPoint); double ePar = arc.GetParameterOf(arc.EndPoint); double length = arc.GetLength(sPar, ePar); double radians = length / arc.Radius; int nrOfSamples = (int)(radians / 0.04); if (nrOfSamples < 3) { if (i == 0) { points.Add(arc.StartPoint); } points.Add(arc.EndPoint); } else { Point2d[] samples = arc.GetSamplePoints(nrOfSamples); if (i != 0) { samples = samples.Skip(1).ToArray(); } foreach (Point2d p2d in samples) { points.Add(p2d); } } break; case SegmentType.Coincident: case SegmentType.Point: case SegmentType.Empty: default: continue; } } PointD[] shapePoints = points.Select(p => new PointD(p.X, p.Y)).ToArray(); string[] attributes = new string[4]; psm.GetOrAttachPropertySet(pline); attributes[0] = psm.ReadPropertyString(driOmråder.Vejnavn); attributes[1] = psm.ReadPropertyString(driOmråder.Vejklasse); attributes[2] = psm.ReadPropertyString(driOmråder.Belægning); attributes[3] = psm.ReadPropertyString(driOmråder.Nummer); writer.AddRecord(shapePoints, shapePoints.Length, attributes); } } #endregion } catch (System.Exception ex) { tx.Abort(); Log.log($"EXCEPTION!!!: {ex.ToString()}. Aborting export of current file!"); //editor.WriteMessage("\n" + ex.Message); return; } tx.Abort(); } }