private static void TestReadHttpConn() { //Open a web file... //------------------------------------- var oWebDBF = new DbfFile(Encoding.GetEncoding(1252)); var oWebFile = new WebClient(); oWebDBF.Open(oWebFile.OpenRead("http://private.socialexplorer.com/State_vars1.dbf")); //read and print records to screen... var orecWeb = new DbfRecord(oWebDBF.Header); var ofs2 = new FileStream(Path.Combine(TestPath, "Webfile.txt"), FileMode.Create); var osw2 = new StreamWriter(ofs2); bool bIsForwardOnly = oWebDBF.IsForwardOnly; bool bIsReadOnly = oWebDBF.IsReadOnly; while (oWebDBF.ReadNext(orecWeb)) { osw2.WriteLine("index: " + orecWeb.RecordIndex + ": " + orecWeb); } osw2.Flush(); osw2.Close(); oWebDBF.Close(); }
private DbfFile OpenReader() { var dbf = new DbfFile(); dbf.Open(GetWorkingFileName(), System.IO.FileMode.Open); return(dbf); }
public new static ShapefileDataWriter Open(string path) { ShapefileHeader header; int recordNumber; using (BinaryReader reader = new BinaryReader(new FileStream(Path.ChangeExtension(path, ".shx"), FileMode.Open))) { header = ShapefileHeader.Read(reader); recordNumber = ((int)(reader.BaseStream.Length - 100) / 8) + 1; } ShapefileDataWriter writer = new ShapefileDataWriter(path, header, FileMode.Append, FileAccess.Write); writer._writerShape.BaseStream.Seek(0, SeekOrigin.End); writer._writerIndex.BaseStream.Seek(0, SeekOrigin.End); writer._recordNumber = recordNumber; writer._filePos = (int)writer._writerShape.BaseStream.Length / 2; // Need to push dbf reader to end of file. writer._dbf = DbfFile.Open(Path.ChangeExtension(path, ".dbf")); writer._currentRecord = new DbfRecord(writer._dbf.Header); return(writer); }
public ShapefileDataReader(string path, IGeometryFactory geometryFactory = null, GeometryTransform transform = null) : base(path, geometryFactory, transform) { _dbf = DbfFile.Open(Path.ChangeExtension(path, ".dbf")); _currentRecord = new DbfRecord(_dbf.Header); }
public DBF(String path, List <Xml_DbfField> dbfFields, Encoding encoding = null) { this.dbfFields = dbfFields; this.path = path; if (encoding == null) { encoding = Encoding.GetEncoding(866); } if (dbfFields == null) { throw new ArgumentNullException(nameof(dbfFields)); } if (path == null) { throw new ArgumentNullException(nameof(path)); } odbf = new DbfFile(encoding); odbf.Open(path, FileMode.Create); // FileMode.Create = файл будет перезаписан если уже существует Logger.info($"Создаём DBF по пути: {path}"); Logger.debug("и кодировкой: {encoding}"); try { writeHeader(); } catch (ArgumentNullException ex) { Logger.error("Исключение ArgumentNullException: " + ex.ParamName); delete(); throw; } }
public void IsDataCorrect() { DbfFile dbfFile = new DbfFile(encoding); dbfFile.Open(dbfFileName, FileMode.Open); DbfRecord orec = new DbfRecord(dbfFile.Header); Assert.IsTrue(dbfFile.ReadNext(orec)); Assert.AreEqual(DbfColumn.DbfColumnType.Character, orec.Column(0).ColumnType); Assert.AreEqual(DbfColumn.DbfColumnType.Number, orec.Column(1).ColumnType); Assert.AreEqual(DbfColumn.DbfColumnType.Date, orec.Column(2).ColumnType); // DBF возвращает строки такой длины, какая указана в хедерах при создании string fio = "Ivanov Ivan Ivanovich"; Assert.AreEqual(fio + new String(' ', 40 - fio.Length), orec[0]); string num = "12.3456"; Assert.AreEqual(new String(' ', 10 - num.Length) + num, orec[1]); Assert.AreEqual("20011122", orec[2]); }
public static void Init(string path_root) { PathDirectory = path_root + @"DBF\"; if (!Directory.Exists(PathDirectory)) { Directory.CreateDirectory(PathDirectory); } var afs = Directory.GetFiles(PathDirectory, "*.dbf"); if (afs.Length > 0) { for (int k = 0; k < afs.Length; k++) { string fi = afs[k]; var odbf = new DbfFile(Encoding.GetEncoding(1252)); odbf.Open(fi, FileMode.Open); //State_vars1.dbf county_vars1.dbf //read and print records to screen... var orec = new DbfRecord(odbf.Header); for (int i = 0; i < odbf.Header.RecordCount; i++) { if (!odbf.Read(i, orec)) { break; } //osw.WriteLine("index: " + orec.RecordIndex + ": " + orec); string ji = orec.ToJson(); } } } }
private static void DbfTestWrite(string filepath) { //编码Encoding.UTF8 中文字符占三字节 Encoding.GetEncoding(936) Encoding.Default中文字符占二字节 var odbf = new DbfFile(Encoding.GetEncoding(936)); odbf.Open(filepath, FileMode.Create);//FileMode.Create OpenOrCreate //创建列头 //odbf.Header.AddColumn(new DbfColumn("编号", DbfColumn.DbfColumnType.Character, 20, 0)); //odbf.Header.AddColumn(new DbfColumn("名称", DbfColumn.DbfColumnType.Character, 20, 0)); //odbf.Header.AddColumn(new DbfColumn("地址", DbfColumn.DbfColumnType.Character, 20, 0)); //odbf.Header.AddColumn(new DbfColumn("时间", DbfColumn.DbfColumnType.Date)); //odbf.Header.AddColumn(new DbfColumn("余额", DbfColumn.DbfColumnType.Number, 15, 3)); //var orec = new DbfRecord(odbf.Header) { AllowDecimalTruncate = true }; //List<User> list = User.GetList(); ////foreach (var item in list) ////{ //User item=list[0]; // orec[0] = item.UserCode; // orec[1] = item.UserName; // orec[2] = item.Address; // orec[3] = item.date.ToString("yyyy-MM-dd HH:mm:ss"); // orec[4] = item.money.ToString(); // odbf.Write(orec, true); ////} //写入边界 //odbf.Header.AddColumn(new DbfColumn("id", DbfColumn.DbfColumnType.Number, 19, 0)); //var orec = new DbfRecord(odbf.Header) { AllowDecimalTruncate = true }; //orec[0] = 1.ToString(); //odbf.Write(orec, true); //写入图斑 odbf.Header.AddColumn(new DbfColumn("图斑编码", DbfColumn.DbfColumnType.Character, 80, 0)); odbf.Header.AddColumn(new DbfColumn("措施代码", DbfColumn.DbfColumnType.Character, 80, 0)); odbf.Header.AddColumn(new DbfColumn("措施名称", DbfColumn.DbfColumnType.Character, 80, 0)); odbf.Header.AddColumn(new DbfColumn("利用现状", DbfColumn.DbfColumnType.Character, 80, 0)); odbf.Header.AddColumn(new DbfColumn("措施数量", DbfColumn.DbfColumnType.Number, 18, 15)); odbf.Header.AddColumn(new DbfColumn("坡度", DbfColumn.DbfColumnType.Number, 18, 15)); var orec = new DbfRecord(odbf.Header) { AllowDecimalTruncate = true }; List <MapPolygon> list = MapPolygon.GetList(); foreach (var item in list) { //MapPolygon item = list[0]; orec[0] = item.Code;//顺序要与header顺序保持一致 orec[1] = item.Mark; orec[2] = item.Name; orec[3] = item.State; orec[4] = item.Number.ToString(); orec[5] = item.Slope.ToString(); odbf.Write(orec, true); } odbf.Close(); }
public static async Task <ShapefileDataSource <T> > CreateAsync(string shapefileName, Func <SqlGeometry, Dictionary <string, object>, T> map, Func <T, List <Object> > inverseAttributeMap, SrsBase targetSrs = null, Encoding encoding = null) { var attributes = DbfFile.Read(ShapefileFormat.Shapefile.GetDbfFileName(shapefileName), true, encoding); var geometries = await ShapefileFormat.Shapefile.ReadShapesAsync(shapefileName); return(new ShapefileDataSource <T>(shapefileName, geometries, attributes, map, inverseAttributeMap, targetSrs)); }
public override void Dispose() { if (_dbf != null) { _dbf.Dispose(); _dbf = null; } base.Dispose(); }
private DbfFile createDBFGageLocationFile(string file) { DbfFile dbf = new DbfFile(); dbf.Open(file, FileMode.Create); dbf.Header.AddColumn(new DbfColumn("ID", DbfColumn.DbfColumnType.Number, 8, 0)); //integer is a binary Integer type dbf.Header.AddColumn(new DbfColumn("NAME", DbfColumn.DbfColumnType.Character, 8, 0)); dbf.Header.AddColumn(new DbfColumn("LAT", DbfColumn.DbfColumnType.Number, 8, 3)); dbf.Header.AddColumn(new DbfColumn("LONG", DbfColumn.DbfColumnType.Number, 8, 3)); dbf.Header.AddColumn(new DbfColumn("ELEVATION", DbfColumn.DbfColumnType.Number, 4, 0));//integer is a binary Integer type return(dbf); }
ITableStructure GetStructure(DbfFile dbf) { var res = new TableStructure(); //output column names for (int i = 0; i < dbf.Header.ColumnCount; i++) { DbTypeBase type; // convert DBF type to DA type switch (dbf.Header[i].ColumnType) { case DbfColumn.DbfColumnType.Binary: type = new DbTypeBlob(); break; case DbfColumn.DbfColumnType.Boolean: type = new DbTypeLogical(); break; case DbfColumn.DbfColumnType.Date: type = new DbTypeDatetime { SubType = DbDatetimeSubType.Date }; break; case DbfColumn.DbfColumnType.Character: type = new DbTypeString { Length = dbf.Header[i].Length }; break; case DbfColumn.DbfColumnType.Integer: type = new DbTypeInt(); break; case DbfColumn.DbfColumnType.Memo: type = new DbTypeText(); break; case DbfColumn.DbfColumnType.Number: type = new DbTypeNumeric { Precision = dbf.Header[i].DecimalCount }; break; default: type = new DbTypeString(); break; } res.AddColumn(dbf.Header[i].Name, type); } return(res); }
public static void SaveAsShapefile <T>(string shpFileName, IEnumerable <Feature <T> > features, SrsBase srs = null) where T : IPoint, new() { var shapes = features.Select(f => f.TheGeometry.AsEsriShape()); Save(shpFileName, shapes, false, true, srs); var dbfFile = GetDbfFileName(shpFileName); var attributes = features.Select(f => f.Attributes).ToList(); DbfFile.Write(dbfFile, attributes, Encoding.GetEncoding(1256), true); }
public static void SaveAsShapefile(string shpFileName, IEnumerable <Msh.Common.Model.GeoJson.GeoJsonFeature> features, bool isLongitudeFirst = true, SrsBase srs = null) { var shapes = features.Select(f => f.Geometry.AsEsriShape(isLongitudeFirst, srs.Srid)); Save(shpFileName, shapes, false, true, srs); var dbfFile = GetDbfFileName(shpFileName); var attributes = features.Select(f => f.Properties).ToList(); DbfFile.Write(dbfFile, attributes, Encoding.GetEncoding(1256), true); }
//public static void Save<T>(string shpFileName, IEnumerable<T> objects, Func<T, IEsriShape> map, bool createDbf = false, bool overwrite = false) //{ // if (objects.IsNullOrEmpty()) // { // return; // } // IEsriShapeCollection collection = new EsriShapeCollection<IEsriShape>(objects.Select(o => map(o))); // Save(shpFileName, collection, createDbf, overwrite); //} //public static void Save(string shpFileName, IEnumerable<IEsriShape> shapes, bool createDbf = false, bool overwrite = false) //{ // if (shapes.IsNullOrEmpty()) // { // return; // } // IEsriShapeCollection collection = new EsriShapeCollection<IEsriShape>(shapes); // Save(shpFileName, collection, createDbf, overwrite); //} public static void Save <T>(string shpFileName, IEnumerable <T> values, Func <T, IEsriShape> geometryMap, List <ObjectToDbfTypeMap <T> > attributeMappings, Encoding encoding, SrsBase srs, bool overwrite = false) { SaveAsShapefile(shpFileName, values.Select(v => geometryMap(v)), false, srs, overwrite); DbfFile.Write(GetDbfFileName(shpFileName), values, attributeMappings, encoding, overwrite); }
private DbItemsCollection getRelevantBlocks(bool NonRetain) { DbfFile dbf = new DbfFile(encoding); dbf.Open(blocksPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); DbfRecord record = new DbfRecord(dbf.Header); DbItemsCollection dbItemsCollection = new DbItemsCollection(); while (dbf.ReadNext(record)) { if (record.IsDeleted) { continue; } try { DbItem dbItem = new DbItem(record, DatabaseType.NormalBlocks); if (dbItem.bBlockType == DbType10 || dbItem.bBlockType == DbType20) //DB { dbItemsCollection.Add(dbItem.DatabaseId, dbItem); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } dbf.Close(); // Remove entries that only contain DbType10 or 20, or where // the attribute is identical. List <int> removeIndexes = new List <int>(); foreach (var blockItem in dbItemsCollection.getDbItems()) { if (!blockItem.Value.ContainsKey(DbType10) || !blockItem.Value.ContainsKey(DbType20) || blockItem.Value[DbType10].currentNonRetain == NonRetain) { removeIndexes.Add(blockItem.Key); } } foreach (var key in removeIndexes) { dbItemsCollection.Remove(key); } return(dbItemsCollection); }
private DbfFile CreateAttr(string path, string[] pointJson) { //这一块代码是为了将字段名和字段类型分别录入List<string>names和types中去 JObject obj = (JObject)JsonConvert.DeserializeObject(pointJson[0]); string attrtypes = obj["attrtype"].ToString(); string attrs = obj["attr"].ToString(); List <string> names = new List <string>(); List <string> types = new List <string>(); JToken attrtype = (JToken)JsonConvert.DeserializeObject(attrtypes); int listLenhth = 0; foreach (JProperty jp in attrtype) { types.Add(jp.Value.ToString()); listLenhth++; } JToken fieldname = (JToken)JsonConvert.DeserializeObject(attrtypes); foreach (JProperty jp in fieldname) { names.Add(jp.Name.ToString()); } //创建DBF文件并根据字段名创建属性空表 string testPath = path; var odbf = new DbfFile(Encoding.GetEncoding(65001)); odbf.Open(Path.Combine(testPath, "poi.dbf"), FileMode.Create); for (int a = 0; a < listLenhth - 1; a++) { if (types[a] == "double") { odbf.Header.AddColumn(new DbfColumn(names[a], DbfColumn.DbfColumnType.Number, 20, 10)); } else { if (types[a] == "integer") { //odbf.Header.AddColumn(new DbfColumn(names[a], DbfColumn.DbfColumnType.Integer, 20, 10)); odbf.Header.AddColumn(new DbfColumn(names[a], DbfColumn.DbfColumnType.Number, 20, 10)); } else { odbf.Header.AddColumn(new DbfColumn(names[a], DbfColumn.DbfColumnType.Character, 100, 0)); } } } return(odbf); }
public void IsHeadersCorrect() { DbfFile dbfFile = new DbfFile(encoding); dbfFile.Open(dbfFileName, FileMode.Open); Assert.AreEqual(fields.Count, dbfFile.Header.ColumnCount); for (int i = 0; i < fields.Count; i++) { Assert.AreEqual(dbfFile.Header[i].Name, fields[i].name); } }
/// <summary> /// create precipitation and temperature gage location file in txt or dbf file /// </summary> private void createGageLocationFile() { FormatType type = Format; if (type != FormatType.ARCSWAT_DBF && type != FormatType.ARCSWAT_TEXT) { return; } if (_stations == null || _stations.Count == 0) { return; } //for ArcSWAT 2012 text format if (type == FormatType.ARCSWAT_TEXT) { StringBuilder sb_p = new StringBuilder(); StringBuilder sb_t = new StringBuilder(); sb_p.AppendLine("ID,NAME,LAT,LONG,ELEVATION"); sb_t.AppendLine("ID,NAME,LAT,LONG,ELEVATION"); foreach (ECStationInfo info in _stations) { sb_p.AppendLine(info.ToArcSWAT2012CSVGageLocation(true)); //precipitation sb_t.AppendLine(info.ToArcSWAT2012CSVGageLocation(false)); //temperature } string pFileName = "pcp.txt"; string tFileName = "tmp.txt"; using (StreamWriter writer = new StreamWriter(_path + @"\" + pFileName)) writer.Write(sb_p.ToString()); using (StreamWriter writer = new StreamWriter(_path + @"\" + tFileName)) writer.Write(sb_t.ToString()); } else if (type == FormatType.ARCSWAT_DBF) { string pFileName = "pcp.dbf"; string tFileName = "tmp.dbf"; DbfFile pDBF = createDBFGageLocationFile(_path + @"\" + pFileName); DbfFile tDBF = createDBFGageLocationFile(_path + @"\" + tFileName); DbfRecord pRec = new DbfRecord(pDBF.Header); DbfRecord tRec = new DbfRecord(tDBF.Header); foreach (ECStationInfo info in _stations) { info.ToArcSWAT2012CSVGageLocation(pDBF, true); info.ToArcSWAT2012CSVGageLocation(tDBF, false); } pDBF.Close(); tDBF.Close(); } }
public static ShapefileDataWriter Create(string path, DbfHeader dbfHeader, ShapefileHeader shapeHeader) { ShapefileDataWriter writer = new ShapefileDataWriter(path, shapeHeader, FileMode.CreateNew, FileAccess.Write); writer._writerShape.BaseStream.Seek(100L, SeekOrigin.Begin); writer._writerIndex.BaseStream.Seek(100L, SeekOrigin.Begin); writer._dbf = DbfFile.Create(Path.ChangeExtension(path, ".dbf"), dbfHeader); writer._currentRecord = new DbfRecord(dbfHeader); writer._recordNumber = 1; writer._filePos = 50; return(writer); }
public DbfFileWriter(String fileName, Encoding fileEncoding, IList <ColumnRelation> columnRelations) { var columnLength = columnRelations.Where(r => !r.FileColumnLength.HasValue).Count(); if (columnLength > 0) { throw new Exception("File Column Length must not be empty."); } _disposed = false; _fileName = fileName; _fileEncoding = fileEncoding; _columnRelations = columnRelations; _file = new DbfFile(fileEncoding); _file.Open(fileName, FileMode.Create); }
public ActionResult DownloadCategoryDbf() { try { DataTable dtCategory = new DataTable("CT_CATEGORY"); DataColumn dcCode = dtCategory.Columns.Add("CODE", typeof(string)); dcCode.MaxLength = 100; DataColumn dcName = dtCategory.Columns.Add("NAME", typeof(string)); dcName.MaxLength = 250; DataColumn dcOrd = dtCategory.Columns.Add("ORD", typeof(int)); dcOrd.Caption = "[25]"; var categories = (from ct in repository.Categories select new { Code = ct.Code, Name = ct.Name, Ord = ct.Ord ?? int.MaxValue }).ToList(); foreach (var category in categories) { DataRow row = dtCategory.NewRow(); row.SetField <string>("CODE", category.Code); row.SetField <string>("NAME", category.Name); row.SetField <int>("ORD", category.Ord); dtCategory.Rows.Add(row); } var ms = new MemoryStream(); DbfFile.DataTableToDbf(dtCategory, ms); var stream = new StreamWithName() { Stream = ms, FileName = "Category.dbf" }; return(File(stream.Stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Soap, stream.FileName)); } catch { return(RedirectToAction("Categories")); } }
/// <summary> /// this method is called to obtain format of input file /// </summary> /// <returns></returns> protected override ITableStructure DoGetRowFormat() { DbfFile dbf = null; try { dbf = OpenReader(); return(GetStructure(dbf)); } finally { if (dbf != null) { dbf.Close(); } } }
/// <summary> /// Update SUBBLK.DBF /// This file contains the all blocks, which contains /// the actual NonRetain attribute and timestamp /// that will be shown in the block online. /// </summary> /// <param name="dbItemsCollection"></param> /// <param name="NonRetain"></param> /// <param name="newTime"></param> private void updateBlockItemsAttr( DbItemsCollection dbItemsCollection, bool NonRetain, string newTime = null) { DbfFile dbf = new DbfFile(encoding); dbf.Open(blocksPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); foreach (var blockItems in dbItemsCollection.getDbItems().Values) { if (!blockItems.ContainsKey(DbType10)) { continue; } // Update only if the current attribute state is different from the given one. if (!blockItems[DbType10].currentNonRetain == NonRetain) { // update reader with the saved record DbfRecord rec = dbf.Read(blockItems[DbType10].recIndex); // Modify the record stored in memory blockItems[DbType10].updateDbItemAttribute( rec, NonRetain, newTime); // Write the modified record to the database dbf.Update(rec); if (blockItems.ContainsKey(DbType20)) { // update reader with the saved record rec = dbf.Read(blockItems[DbType20].recIndex); // Modify the record stored in memory blockItems[DbType20].updateDbItemAttribute( rec, NonRetain, newTime); // Write the modified record to the database dbf.Update(rec); } } else { } } dbf.Close(); }
/// <summary> /// reads content of input file into given data queue /// </summary> /// <param name="queue"></param> protected override void DoRead(IDataQueue queue) { DbfFile dbf = null; try { dbf = OpenReader(); ITableStructure format = GetStructure(dbf); DbfRecord irec = new DbfRecord(dbf.Header); // for each record in input DBF while (dbf.ReadNext(irec)) { if (irec.IsDeleted) { continue; } object[] vals = new object[format.Columns.Count]; for (int i = 0; i < format.Columns.Count; i++) { vals[i] = irec[i]; } var orec = new ArrayDataRecord(format, vals); queue.PutRecord(new ArrayDataRecord(format, vals)); } queue.PutEof(); } catch (Exception e) { ProgressInfo.LogError(e); queue.PutError(e); } finally { if (dbf != null) { dbf.Close(); } queue.CloseWriting(); } FinalizeBulkCopy(); }
private static void DbfTestRead(string filepath) { //编码Encoding.UTF8 中文字符占三字节 Encoding.GetEncoding(936)中文字符占二字节 var odbf = new DbfFile(Encoding.GetEncoding(936));//编码 odbf.Open(filepath, FileMode.Open); DbfHeader header = odbf.Header; Console.WriteLine(header.ColumnCount); //List<User> list = new List<User>(); //for (int i = 0; i < header.RecordCount; i++) //{ // DbfRecord record = odbf.Read(i); // if (record.ColumnCount >= 5) // { // User item = new User(); // item.Address = record["地址"].Trim();//record.Column(record.FindColumn("编号")); // item.date = record.GetDateValue(record.FindColumn("时间")); // item.money = Convert.ToDecimal(record["余额"]); // item.UserCode = record["编号"].Trim(); // item.UserName = record["名称"].Trim(); // list.Add(item); // } //} List <MapPolygon> list = new List <MapPolygon>(); for (int i = 0; i < header.RecordCount; i++) { DbfRecord record = odbf.Read(i); if (record.ColumnCount >= 5) { MapPolygon item = new MapPolygon(); item.Code = record[record.FindColumEx("图斑编码")].Trim(); // record["图斑编码"].Trim();//record.Column(record.FindColumn("编号")); item.Mark = record[record.FindColumEx("措施代码")].Trim(); //record["措施代码"].Trim(); item.Name = record[record.FindColumEx("措施名称")].Trim(); //record["措施名称"].Trim(); item.State = record[record.FindColumEx("利用现状")].Trim(); //record["利用现状"].Trim(); //item.Number =Convert.ToSingle( record["措施数量"]); //item.Slope = Convert.ToSingle(record["坡度"]); list.Add(item); } } Console.Read(); }
public override DataTable Load(string filePath, params object[] param) { DataTable dt = new DataTable(); using (FileStream fs = new FileStream(filePath, FileMode.Open)) { DbfFile file = new DbfFile(); if (file.ReadStream(fs) != true) { throw new Exception("Failed to read DBF file."); } file.DataTable.TableName = Path.GetFileNameWithoutExtension(filePath); file.DataTable.AddDataSource(Path.GetFileName(filePath)); dt = file.DataTable; } return(dt); }
//从源文件获取字段信息 public List <R_FieldInf> GetFieldInfs(string path) { List <R_FieldInf> FieldInfs = new List <R_FieldInf>(); string dbfpath = path; #region 该部分使用FastDBF获取字段名称 返回List<string> fieldNames DbfFile dbf = new DbfFile(Encoding.Default); dbf.Open(dbfpath, FileMode.Open); DbfHeader dh = dbf.Header; List <string> fieldNames = new List <string>(); int fieldCount = dh.ColumnCount; for (int index = 0; index < fieldCount; index++) { fieldNames.Add(dh[index].Name); } dbf.Close(); #endregion #region 该部分使用Shapelib获取字段类型 返回List<string> fieldTypes //获取字段类型 IntPtr hDbf = ShapeLib.DBFOpen(dbfpath, "rb+");//"rb"(只读)"rb+"(读/写) int pointCount = ShapeLib.DBFGetRecordCount(hDbf); List <string> fieldTypes = new List <string>(); StringBuilder stringBuilder = new StringBuilder(20); int pnWidth = 10; int pnDecimals = 10; for (int index = 0; index < fieldCount; index++) { string type = TypeConvert(ShapeLib.DBFGetFieldInfo(hDbf, index, stringBuilder, ref pnWidth, ref pnDecimals).ToString()); fieldTypes.Add(type); } ShapeLib.DBFClose(hDbf); #endregion //实例化类型 for (int index = 0; index < fieldCount; index++) { FieldInfs.Add(new R_FieldInf(fieldNames[index], fieldTypes[index])); } return(FieldInfs); }
public string CreateDbfFile(RegistryInfo registryInfo) { try { var workDirectory = Path.Combine(Directory.GetCurrentDirectory(), @"Abonents\" + registryInfo.Now.ToString("dd.MM.yyyy")); var dbfFilePath = Path.Combine(workDirectory, $"{registryInfo.FileName}" + ".dbf"); if (!Directory.Exists(workDirectory)) { Directory.CreateDirectory(workDirectory); } if (File.Exists(dbfFilePath)) { File.Delete(dbfFilePath); } var dbfFile = new DbfFile(); dbfFile.Create(dbfFilePath); dbfFile.Header.Unlock(); dbfFile.Header.AddColumn("FIO", DbfColumn.DbfColumnType.Character, 100, 0); dbfFile.Header.AddColumn("ACCOUNT", DbfColumn.DbfColumnType.Character, 20, 0); var record = new DbfRecord(dbfFile.Header, Encoding.GetEncoding(1251)) { }; foreach (Abonent row in registryInfo.Abonents) { record[0] = row.Fio; record[1] = row.Account; dbfFile.Write(record, true); } dbfFile.Close(); return(dbfFilePath); } catch (Exception ex) { throw new Exception($"Error in CreateDbfFile: {ex}"); } }
static void Main(string[] args) { // Einfache Datenbank erstellen var odbf = new DbfFile(Encoding.GetEncoding(1252)); odbf.Open(Path.Combine(TestPath, "libfintx.dbf"), FileMode.Create); // Header erstellen odbf.Header.AddColumn(new DbfColumn("StrCol", DbfColumn.DbfColumnType.Character, 20, 0)); odbf.Header.AddColumn(new DbfColumn("DecCol1", DbfColumn.DbfColumnType.Number, 5, 1)); odbf.Header.AddColumn(new DbfColumn("DecCol2", DbfColumn.DbfColumnType.Number, 5, 2)); odbf.Header.AddColumn(new DbfColumn("DecCol3", DbfColumn.DbfColumnType.Number, 5, 3)); odbf.Header.AddColumn(new DbfColumn("DecCol4", DbfColumn.DbfColumnType.Number, 15, 5)); odbf.Header.AddColumn(new DbfColumn("NumCol1", DbfColumn.DbfColumnType.Number, 5, 0)); odbf.Header.AddColumn(new DbfColumn("NumCol2", DbfColumn.DbfColumnType.Number, 10, 0)); odbf.Header.AddColumn(new DbfColumn("DateCol1", DbfColumn.DbfColumnType.Date)); odbf.Header.AddColumn(new DbfColumn("BoolCol1", DbfColumn.DbfColumnType.Boolean)); // Datensatz hinzufügen var orec = new DbfRecord(odbf.Header) { AllowDecimalTruncate = true }; orec[0] = "Torsten Klinger"; orec[1] = "123.5"; orec[2] = "12.35"; orec[3] = "1.235"; orec[4] = "1235.123456"; orec[5] = "1235"; orec[6] = "123567890"; orec[7] = "11/07/2020"; orec[8] = "f"; odbf.Write(orec, true); // Verbindung schließen odbf.Close(); }