批量替换cad文件里面的文字
public void OandS(){
string fdbname = "";
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK)
{
fdbname = fbd.SelectedPath;
}
if (result == DialogResult.Cancel) { return; }
DirectoryInfo fldinfo = new DirectoryInfo(fdbname);
FileInfo[] files = fldinfo.GetFiles("*.dwg");
foreach (var f in files)
{
//Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
using (Database db = new Database(false, true))
using (Transaction trans = db.TransactionManager.StartTransaction())
{
string filename = f.FullName;
string filename2 = @"C:\Users\Administrator\Desktop\dwgout"+"\\"+f.Name;
if (System.IO.File.Exists(filename))
{
db.ReadDwgFile(filename, System.IO.FileShare.ReadWrite, true, null);
/*
LayerTable lt = (LayerTable) db.LayerTableId.GetObject(OpenMode.ForRead);
foreach (ObjectId id in lt )
{
LayerTableRecord ltr = (LayerTableRecord) id.GetObject(OpenMode.ForRead);
if(ltr != null) ed.WriteMessage("\n" + ltr.Name);
}
*/
BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
BlockTableRecord btr =
(BlockTableRecord)trans.GetObject(bt, OpenMode.ForWrite);
foreach (ObjectId id in btr)
{
Entity ent = (Entity)trans.GetObject(id, OpenMode.ForWrite);
string enttype = ent.GetType().ToString();
if (ent.Layer.ToString() == "TK" && enttype == "Autodesk.AutoCAD.DatabaseServices.DBText")
{
DBText dbtext = ent as DBText;
if (dbtext.TextString.Contains("航测成图"))
{
ent.Erase();
//dbtext.TextString = "测试";
DBText newtext = new DBText();
newtext.Position = dbtext.Position;
newtext.Height = dbtext.Height;
newtext.TextString = dbtext.TextString.Replace("航测", "缩编");
newtext.HorizontalMode = dbtext.HorizontalMode;
newtext.VerticalMode = dbtext.VerticalMode;
newtext.AlignmentPoint = dbtext.AlignmentPoint;
newtext.TextStyleId = dbtext.TextStyleId;
db.AddToModelSpace(newtext);
}
}
}
db.SaveAs(filename2, DwgVersion.AC1800);
trans.Commit();
}
}
}
System.Windows.Forms.MessageBox.Show("文字替换转换完成!");
}
页:
[1]