using System; 
using System.IO; 
using Autodesk.AutoCAD.Runtime; 
using Autodesk.AutoCAD.ApplicationServices; 
using Autodesk.AutoCAD.DatabaseServices; 
using Autodesk.AutoCAD.EditorInput; 
 
namespace ClassLibrary2 
{ 
        public class Class1 
    { 
        [CommandMethod("dpSaveLayoutsToSeparateFiles2")] 
        public void dpSaveLayouts2() 
        { 
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; 
            Document doc = Application.DocumentManager.MdiActiveDocument; 
            HostApplicationServices hs = HostApplicationServices.Current; 
            Database db = Application.DocumentManager.MdiActiveDocument.Database; 
 
            //системная переменная, проверяем сохранен ли файл или нет 
            object DWGTITLED = Application.GetSystemVariable("DWGTITLED"); 
 
            //если не сохранен выходим 
            if (System.Convert.ToInt16(DWGTITLED) == 0) 
            { 
                Application.ShowAlertDialog("Перед использованием процедуры сохранить"); 
                return; 
            } 
 
            //получаем полный путь к DWG файлу 
            string dwgFullPath = hs.FindFile(doc.Name, doc.Database, FindFileHint.Default); 
            //получаем имя DWG файла 
            string dwgName = Path.GetFileName(dwgFullPath); 
            //получаем имя DWG файла без расширения 
            string dwgNameWoExt = Path.GetFileNameWithoutExtension(dwgFullPath); 
            //получаем путь к DWG файлу 
            string dwgPath = Path.GetDirectoryName(dwgFullPath); 
            //путь для сохранения новых DWG файлов 
            string dwgNewFullPath = ""; 
            //получаем путь к TEMP 
            string tempPath = System.IO.Path.GetTempPath(); 
 
            //блокируем документ 
            using (DocumentLock doclock = doc.LockDocument()) 
            { 
                //пошла транзакция 
                using (Transaction tr = db.TransactionManager.StartTransaction()) 
                { 
                    { 
                        //получаем коллекцию Layout 
                        DBDictionary acLayouts = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary; 
                        //получаем количество вкладок 
                        int layoutsCount = acLayouts.Count; 
                        LayoutManager acLayoutMgr; 
                        acLayoutMgr = LayoutManager.Current; 
                        //перебираем все вкладки 
                        foreach (DBDictionaryEntry item in acLayouts) 
                        { 
                            //имя лейаута 
                            String layoutName = item.Key; 
                            //получаем Лейаут 
                            Layout acLayout = tr.GetObject(item.Value, OpenMode.ForRead) as Layout; 
 
                            //если не модель то идем дальше 
                            if (acLayout.LayoutName.ToUpper() != "MODEL" && acLayout.LayoutName.ToUpper() != "МОДЕЛЬ") 
                            { 
                                //acLayoutMgr.CurrentLayout = acLayout.LayoutName; 
                                //активируем вкладку 
                                acLayoutMgr.CurrentLayout = acLayout.LayoutName; 
                                //получаем систменую переменную отображеня вывода в консоль 
                                Object CMDECHO = Application.GetSystemVariable("CMDECHO"); 
                                //запрещаем вывод в консоль 
                                Application.SetSystemVariable("CMDECHO", 0); 
                                //создаем путь к нашему новому файлу 
                                dwgNewFullPath = dwgPath + "" + dwgNameWoExt + "_[" + acLayout.LayoutName + "]_.dwg"; 
                                //сохраняем файл и экранируем слеши 
                                db.SaveAs(dwgNewFullPath.Replace("", "\\"), DwgVersion.AC1021); 
 
                                //////////////////**/////////////////////////////////////////////////*/*/////////////// 
                                Database db2 = new Database(false, true); 
                                db2.ReadDwgFile(dwgNewFullPath, FileOpenMode.OpenForReadAndWriteNoShare, false, ""); 
                                using (Transaction tr2 = db2.TransactionManager.StartTransaction()) 
                                { 
                                    db2.SaveAs(dwgNewFullPath.Replace("", "\\"), DwgVersion.Current); 
                                    tr2.Commit(); 
                                } 
                                //////////////////**/////////////////////////////////////////////////*/*/////////////// 
 
                                //восстанавливаем систменую переменную отображеня вывода в консоль 
                                Application.SetSystemVariable("CMDECHO", CMDECHO); 
                                //dpDelLayoutsFrom**DWG(dwgTempPath, dwgNewFullPath); 
                                ed.WriteMessage("Сохранено: " + dwgNewFullPath + "\n"); 
                            } 
                        } 
                    } 
                    tr.Commit(); 
                } 
            } 
        } 
    } 
}