Try this code
[CommandMethod("txtdata", CommandFlags.Modal | CommandFlags.UsePickSet)]
public void TextDataExtraction()
{
StringBuilder sb = new StringBuilder();
List<string[]> data = new List<string[]>();
// get active drawing
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
// get document editor
Editor ed = doc.Editor;
// build selection filter , put layers you need, separated by commas
//SelectionFilter sfilter= new SelectionFilter(new TypedValue[]{new TypedValue(0,"text"),new TypedValue(8,"Layer1,Layer2,Layer999")});
// to select all text on all alyers you have to elimminate second typedvalue from filter:
SelectionFilter sfilter = new SelectionFilter(new TypedValue[] { new TypedValue(0, "text") });
// request for objects to be selected in the whole drawing
PromptSelectionResult res = ed.SelectAll(sfilter);
try
{
//check on valid selection result
if (res.Status == PromptStatus.OK)
{
//get object transaction
using (Transaction tr = doc.TransactionManager.StartTransaction())
{
foreach (ObjectId id in res.Value.GetObjectIds())
{
Entity ent = tr.GetObject(id, OpenMode.ForRead, false) as Entity;
DBText txt = ent as DBText;
if (txt != null)
{
//if text has an empty string it will be replaced with "---"
string record = string.Format("{0}\t{1:f2}\t{2:f2}\n", txt.TextString == "" ? "---" : txt.TextString, txt.Position.X, txt.Position.Y);
//add record to string builder
sb.Append(record);
string[] item = new string[3];
item[0] = txt.TextString == "" ? "---" : txt.TextString;//<--- if text has an empty string it will be replaced with "---"
item[1] = string.Format("{0:f3}", txt.Position.X);//<--- precision 3 decimals
item[2] = string.Format("{0:f3}", txt.Position.Y);//<--- precision 3 decimals
data.Add(item);
}
}
//write data to CSV file
using (StreamWriter sw = new StreamWriter(@"C:\Test\TextRecords.csv")) //<---change file name here
{
foreach ( string[] record in data)
{
// create tab delimited string
string line = string.Format("{0}\t{1:f2}\t{2:f2}", record[0], record[1], record[2]);
sw.WriteLine(line);
}
sw.Close();
}
tr.Commit();
}
}
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
ed.WriteMessage("\n" + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
}
}