private void CopySolidworksFile(string file_from, string file_to, string replease_from, string replact_to) { ISldWorks swApp = Utility.ConnectToSolidWorks(); string source = System.IO.Path.GetDirectoryName(file_from); string target = System.IO.Path.GetDirectoryName(file_to); string sourcefile = file_from;; string tempfile = System.IO.Path.GetFileName(file_to); bool traverse = false; bool search = false; bool addreadonlyinfo = false; object[] depends = null; string[] sourcefiles = null; string[] targetfiles = null; int idx = 0; int sourcecount = 0; int copyopt = 0; int errors = 0; int lind = 0; ModelDoc2 doc = default(ModelDoc2); // sourcefile = file_from; tempfile = file_to;// System.IO.Path.GetDirectoryName(file_to); lind = tempfile.LastIndexOf("\\"); target = tempfile.Substring(0, lind); traverse = true; search = true; addreadonlyinfo = false; depends = (object[])swApp.GetDocumentDependencies2(sourcefile, traverse, search, addreadonlyinfo); if ((depends == null)) { return; } idx = 1; while (idx <= depends.GetUpperBound(0)) { Array.Resize(ref sourcefiles, sourcecount + 1); Array.Resize(ref targetfiles, sourcecount + 1); sourcefiles[sourcecount] = (string)depends[idx]; lind = sourcefiles[sourcecount].LastIndexOf("\\"); targetfiles[sourcecount] = target + sourcefiles[sourcecount].Substring(lind, sourcefiles[sourcecount].Length - lind); sourcecount = sourcecount + 1; idx = idx + 2; } swApp.CloseAllDocuments(true); copyopt = (int)swMoveCopyOptions_e.swMoveCopyOptionsOverwriteExistingDocs; errors = swApp.CopyDocument(sourcefile, target + @"\" + System.IO.Path.GetFileName(sourcefile), (sourcefiles), (targetfiles), (int)copyopt); }
internal static void OpenDoc() { if (swApp != null) { ISldWorks iSwApp = (ISldWorks)swApp; iSwApp.CloseAllDocuments(true); swDoc = (ModelDoc2)swApp.INewPart(); swDoc.SetUnits((short)swLengthUnit_e.swMM, (short)swFractionDisplay_e.swDECIMAL, 0, 0, false); } }
public static void Start(string installDirectory, string programStatePath, string GUIconfigPath, string DDTOpath) { /* * This program listens for a 'call to action bool' * - the second character in a string from the * - run state config file for this MS * On TRUE it reads the DDTO, which the GUI MS * will have sent the current set of expressions to * evaluate, then set the GUI's call to action state * to false - meaning it cannot write to the DDTO, * though it will store the command and do it asap, * then this daemon will read the DDTO and implement * the expressions in it, after it resets its own * and the GUI's call to action, turning itself off * and the GUI's write ability on */ RunState programState; Console.WriteLine(" -- Daemon - Start --"); try { do { programState = RunState.GetProgramState(programStatePath); if (programState.GetActionState()) { CloseGUIsemaphore(GUIconfigPath); var PROG_ID = "SldWorks.Application.24"; var swType = Type.GetTypeFromProgID(PROG_ID); ValidateSWtype(swType); swApp = (ISldWorks)Activator.CreateInstance(swType); CreateSWAppInstance(swApp); var blobName = programState.GetBlobName(); var blobPath = installDirectory + "blob\\" + blobName; DocumentSpecification documentSpecification = SWDocSpecification.GetDocumentSpecification(swApp, blobPath); if (documentSpecification == null) { Console.WriteLine("Could not Get Document Specification for - " + blobPath); return; } Console.WriteLine(" - Obtained Document Specification for - " + blobPath); var model = swApp.OpenDoc7( documentSpecification); if (model == null) { Console.WriteLine(" - ERROR - Could not Open Document - " + blobPath); return; } Console.WriteLine(" - Opened SolidWorks Document - " + blobPath); EquationMgr equationManager = model.GetEquationMgr(); if (equationManager == null) { Console.WriteLine("Could Not Get Equation Manager Instance"); Console.WriteLine(" - Closing All Open SolidWorks Documents"); swApp.CloseAllDocuments(true); return; } Console.WriteLine(" - Created Equation Manager Instance"); var rawBlempString = Blemp.LoadDDTO(DDTOpath); var writeSuccess = false; var timeOut = 5; if (rawBlempString != null) { var equationSegments = Blemp.GetDDTOequationSegments(rawBlempString); if (equationSegments != null) { Console.WriteLine(" - Valid Equations Found - Processing"); try { for (var i = 0; i < equationSegments.Length; ++i) { SWEquation.AddEquation( equationManager, equationSegments[i] ); SWEquation.Build( model ); SWEquation.DeleteEquation( equationManager, 0); } } catch (ArgumentOutOfRangeException exception) { Console.WriteLine(exception); } } else { Console.WriteLine(" - WARNING - No Valid Equations for Processing Found"); } } else { Console.WriteLine("No Equations Found in DDTO"); } do { Console.WriteLine(" - Closing Call to Action Semaphore"); writeSuccess = FileWrite.WriteStringToFileFalseOnFail( programStatePath, "011!" ); FileWrite.WriteStringToFileFalseOnFail(DDTOpath, ""); Thread.Sleep(300); } while (!writeSuccess && timeOut-- > 0); if (timeOut > 0) { Console.WriteLine(" - Call to Action Semaphore - Successfuly Closed"); } else { Console.WriteLine(" - ERROR - Could Not Write Call to Action Close Command"); Console.WriteLine(" - Exiting Daemon -"); Console.WriteLine(" -- Daemon - Exit --"); return; } timeOut = 5; do { Console.WriteLine(" - Opening GUI Call to Action Semaphore"); writeSuccess = FileWrite.WriteStringToFileFalseOnFail( GUIconfigPath, "00" ); Thread.Sleep(300); } while (!writeSuccess && timeOut-- > 0); } if (programState.GetCloseBlob()) { CloseGUIsemaphore(GUIconfigPath); if (swApp != null) { swApp.CloseAllDocuments(true); } FileWrite.WriteStringToFileFalseOnFail(programStatePath, "011!"); Console.WriteLine(" - Opening GUI Call to Action Semaphore"); FileWrite.WriteStringToFileFalseOnFail( GUIconfigPath, "00"); } Thread.Sleep(300); } while (programState.GetRunState()); } catch (Exception exception) { Console.WriteLine(exception); } if (swApp != null) { swApp.CloseAllDocuments(true); } Console.WriteLine(" -- Daemon - Exit --"); }
static void Main(string[] args) { // LiveUpdateTest(); var swType = SWType.GetFromProgID(PROG_ID); if (swType == null) { logger.Error("\n ERROR: GetFromProgID returned null\n" + " - Exiting Program"); promptToExitProgram(); return; } ISldWorks swApp = CreateSWInstance.Create(swType); if (swApp == null) { logger.Error("\n ERROR: Could not get reference to " + "SolidWorks App\n - Exiting Program"); promptToExitProgram(); return; } var path = "C:\\Users\\bolinger\\Desktop\\test install\\toppAppDBdaemon\\blob\\C-HSSX.blob.SLDPRT"; DocumentSpecification documentSpecification = SWDocSpecification.GetDocumentSpecification(swApp, path); if (documentSpecification == null) { logger.Error("\n ERROR: Could not Get Document Specification for file: " + path + "\n - Exiting Program"); promptToExitProgram(); return; } logger.Debug("\n Getting Model from Document Specification"); ModelDoc2 model = (ModelDoc2)swApp.OpenDoc7( documentSpecification); if (model == null) { logger.Error("\n ERROR: Could not get Model from " + "Document Specification\n - Exiting Program"); promptToExitProgram(); return; } Config.model = model; logger.Debug("\n Getting Equation Manager from Model"); EquationMgr equationManager = model.GetEquationMgr(); if (equationManager == null) { logger.Error("\n ERROR: Could not get Equation Manager from Model\n" + " - Exiting Program"); promptToExitProgram(); return; } Config.equationManager = equationManager; logger.Debug("\n SolidWorks App Instance Initialized - Starting Microservice Daemon"); Daemon.Start(); promptToExitProgram(); logger.Debug("\n Closing Open SolidWorks Documents" + "\n - Exiting Microservice"); swApp.CloseAllDocuments(true); }
public static void RecopyHeare(SwAddin swAddin, ISldWorks swApp,ModelDoc2 swModelDoc) { try { SwAddin.IsEventsEnabled = false; swModelDoc.Save(); ModelDocExtension swModelDocExt = default(ModelDocExtension); PackAndGo swPackAndGo = default(PackAndGo); Dictionary<string,string> filesToHideAndShow = new Dictionary<string, string>(); WaitTime.Instance.ShowWait(); WaitTime.Instance.SetLabel("Отрыв сборки от библиотеки."); int warnings = 0; int errors = 0; string _openFile = swModelDoc.GetPathName(); swAddin.currentPath = string.Empty; swApp.CloseAllDocuments(true); if (!Directory.Exists("C:\\Temp")) Directory.CreateDirectory("C:\\Temp"); string tempDir = Path.Combine("C:\\Temp", Path.GetFileNameWithoutExtension(_openFile)); if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } Directory.CreateDirectory(tempDir); string fileToOpenTemp = Path.Combine(tempDir, Path.GetFileName(_openFile)); //File.Copy(_openFile, fileToOpenTemp); Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(Path.GetDirectoryName(_openFile), tempDir); if (!File.Exists(fileToOpenTemp)) { throw new Exception("Ошибка. Не найден файл: " + fileToOpenTemp); } swAddin.DetachEventHandlers(); swModelDoc = (ModelDoc2)swApp.OpenDoc6(fileToOpenTemp, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors, warnings); swAddin.AttachEventHandlers(); try { foreach (var file in Directory.GetFiles(Path.GetDirectoryName(_openFile))) { File.Delete(file); } foreach (var directory in Directory.GetDirectories(Path.GetDirectoryName(_openFile))) { Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(directory, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin); //Directory.Delete(directory, true); } } catch (Exception e) { Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory( tempDir,Path.GetDirectoryName(_openFile),true); swAddin.DetachEventHandlers(); swApp.CloseAllDocuments(true); swModelDoc = (ModelDoc2)swApp.OpenDoc6(_openFile, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors, warnings); swAddin.AttachEventHandlers(); MessageBox.Show(@"Из-за ошибки: """ + e.Message + @""" не удалось оторвать проект. Перезапустите SW и попробуйте еще раз."); return; } //File.Delete(_openFile); swModelDocExt = (ModelDocExtension)swModelDoc.Extension; swPackAndGo = (PackAndGo)swModelDocExt.GetPackAndGo(); //swModelDoc = (ModelDoc2)swApp.OpenDoc6(openFile, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); //swModelDocExt = (ModelDocExtension)swModelDoc.Extension; int namesCount = swPackAndGo.GetDocumentNamesCount(); object fileNames; object[] pgFileNames = new object[namesCount - 1]; bool status = swPackAndGo.GetDocumentNames(out fileNames); string[] newFileNames = new string[namesCount]; string[] rFileNames1 = fileNames as string[]; if (rFileNames1 == null) throw new Exception("Не удалось оторвать заказ."); string[] rFileNames = new string[rFileNames1.Length]; for (int ii = 0; ii < rFileNames1.Length;ii++ ) { var tt1 = Microsoft.VisualBasic.FileSystem.Dir(rFileNames1[ii]); if (tt1==null) tt1 = Microsoft.VisualBasic.FileSystem.Dir(rFileNames1[ii], Microsoft.VisualBasic.FileAttribute.Hidden); rFileNames[ii] = Path.Combine(Path.GetDirectoryName(rFileNames1[ii]),tt1); } //удалить неактуальные программы.. DeleteXmlFiles(tempDir, rFileNames,_openFile); //bool isAuxiliary = (swCompModel.get_CustomInfo2("", "Auxiliary") == "Yes"); //bool isAccessory = (swCompModel.get_CustomInfo2("", "Accessories") == "Yes"); //string strSubCompNewFileName; //if (GetComponentNewFileName(swModel, isAuxiliary, isAccessory, // isFirstLevel, strSubCompOldFileNameFromModel, // out strSubCompNewFileName)) //{ //} string xName = swAddin.GetXNameForAssembly(false, Path.GetFileNameWithoutExtension(_openFile)); string furnDir = Path.Combine(Path.GetDirectoryName(_openFile), "ФУРНИТУРА"); string furnHelpDir = Path.Combine(Path.GetDirectoryName(_openFile), "ФУРНИТУРА", "Модели фурнитуры"); string partDir = Path.Combine(Path.GetDirectoryName(_openFile), "ДЕТАЛИ"); string partDirHelp = Path.Combine(Path.GetDirectoryName(_openFile), "ДЕТАЛИ", "Вспомогательные детали"); string partForAssDir = Path.Combine(Path.GetDirectoryName(_openFile), "ДЕТАЛИ", "Детали для сборок"); //DSOFile.OleDocumentProperties m_oDocument = null; //m_oDocument = new DSOFile.OleDocumentPropertiesClass(); for (int i = 0; i<namesCount;i++) { //вот пример как выглядит массив элементов в fileNames. Переделать их в newFileNames и все... // [0] "c:\\temp\\2222\\2222.sldasm" string //[1] "d:\\_swlib_backup\\крепежная фурнитура\\вспомогательные\\3090_штифт для эксцентрика пластикового 20 мм.sldprt" string //[2] "d:\\_swlib_backup\\крепежная фурнитура\\вспомогательные\\3093_эксцентрик пластиковый для дсп 16 мм 20 мм.sldprt" string //[3] "d:\\_swlib_backup\\крепежная фурнитура\\вспомогательные\\отв для арт. 3090.sldprt" string //[4] "d:\\_swlib_backup\\крепежная фурнитура\\3093+3090_(эксцентрик пластиковый 20 мм для дсп 16 мм+штифт для эксцентрика пластикового 20 мм).sldasm" string //[5] "d:\\_swlib_backup\\шкафы-купе\\каркасные детали\\дсп 16 мм\\вспомогательные\\8504_панель вкладная 000a01p.sldprt" string //[6] "d:\\_swlib_backup\\шкафы-купе\\каркасные детали\\дсп 16 мм\\8504f_панель вкладная 000a01p.sldasm" string //в rFileNames[i] вот что: //d:\_swlib_backup\шкафы-купе\каркасы шкафов-купе\вспомогательные\детали для сборок\Панель боковая правая_K02214P.SLDPRT //если содержит _swlib_backup и на конце 2 цифры + "P" = заменяем эти 2 цифры на 01 и помещаем оба файлика в список //потом пробегусь по списку. 01 - убрать скрытие, для старого - скрыть string fileName = Path.GetFileName(rFileNames[i]); string tmprFileName = rFileNames[i]; if (!Directory.Exists(partDir)) Directory.CreateDirectory(partDir); if (fileName.ToLower().Contains(Path.GetFileName(_openFile.ToLower()))) { newFileNames[i] = _openFile; continue; } if (rFileNames[i].ToLower().Contains(tempDir.ToLower())) { newFileNames[i] = rFileNames[i].Replace(tempDir.ToLower(), Path.GetDirectoryName(_openFile)); continue; } string idCopyTo = rFileNames[i].Substring(rFileNames[i].Length - 10, 2); int newNumber; char lastChar = Path.GetFileNameWithoutExtension(rFileNames[i]).Last(); if ((lastChar != 'p' && lastChar!='P') || !int.TryParse(idCopyTo, out newNumber))//(rFileNames[i].ToLower().Contains("крепежная фурнитура") || rFileNames[i].ToLower().Contains("фурнитура для каркасов")) { if (!Directory.Exists(furnDir)) Directory.CreateDirectory(furnDir); if (rFileNames[i].ToLower().Contains("вспомогательные")) { //2222//ФУРНИТУРА//Модели фурнитуры if (!Directory.Exists(furnHelpDir)) Directory.CreateDirectory(furnHelpDir); newFileNames[i] = Path.Combine(furnHelpDir, Path.GetFileNameWithoutExtension(rFileNames[i]) + " #" + xName+"-1" + Path.GetExtension(rFileNames[i])); continue; } else { //2222//ФУРНИТУРА// newFileNames[i] = Path.Combine(furnDir, Path.GetFileNameWithoutExtension(rFileNames[i]) + " #" + xName +"-1"+ Path.GetExtension(rFileNames[i])); continue; } } else { tmprFileName = GetFileNameWithoutSuff(rFileNames[i]); } string fnext = Path.GetFileNameWithoutExtension(tmprFileName); string[] arr = fnext.Split('-').ToArray(); if (arr.Length != 2) { //учитывать только последний "-" string[] tmp = new string[2]; for (int j = 0; j < arr.Length-1; j++) { tmp[0] = string.Format("{0}-{1}", tmp[0], arr[j]); } tmp[0] = tmp[0].Remove(0, 1); tmp[1] = arr.Last(); arr = tmp; } string newName = arr[0] + " #" + xName+"-" + arr[1] + Path.GetExtension(tmprFileName); if (tmprFileName.ToLower().Contains("вспомогательные")) { //if (true)//(tmprFileName.ToLower().Contains("детали для сборок"))//|| Path.GetExtension(tmprFileName).ToLower()==".sldprt" ) //{ if (!Directory.Exists(partForAssDir)) Directory.CreateDirectory(partForAssDir); newFileNames[i] = Path.Combine(partForAssDir, newName); continue; //} ////2222\ДЕТАЛИ\Вспомогательные детали //if (!Directory.Exists(partDirHelp)) // Directory.CreateDirectory(partDirHelp); //newFileNames[i] = Path.Combine(partDirHelp, newName); //continue; } newFileNames[i] = Path.Combine(partDir, newName); } BStrWrapper[] pgSetFileNames; //тут надо немного поправить newFileNames так, чтобы не было одинаковых.. string[] tmpFileNames = new string[newFileNames.Length]; int jj = 0; foreach (var tmpFileName in newFileNames) { int same = tmpFileNames.Count(f => f!=null ? f.ToLower() == tmpFileName.ToLower() : false); if (same > 0 && !tmpFileName.Contains("фурнитура") && !tmpFileName.Contains("ФУРНИТУРА")) { string tmp = Path.GetFileNameWithoutExtension(tmpFileName).Split('-').LastOrDefault(); if (string.IsNullOrEmpty(tmp)) continue; int tmpNumb; if (!int.TryParse(tmp, out tmpNumb)) continue; int index = Path.GetFileNameWithoutExtension(tmpFileName).IndexOf('-'); string substr = Path.GetFileNameWithoutExtension(tmpFileName).Substring(0, index)+"-"+(tmpNumb+1).ToString() + Path.GetExtension(tmpFileName); string res = Path.Combine(Path.GetDirectoryName(tmpFileName), substr); next: same = tmpFileNames.Count(f => f != null ? f.ToLower() == res.ToLower() : false); if (same > 0) { tmp = Path.GetFileNameWithoutExtension(res).Split('-').LastOrDefault(); if (string.IsNullOrEmpty(tmp)) continue; if (!int.TryParse(tmp, out tmpNumb)) continue; index = Path.GetFileNameWithoutExtension(res).IndexOf('-'); substr = Path.GetFileNameWithoutExtension(res).Substring(0, index) + "-" + (tmpNumb + 1).ToString() + Path.GetExtension(tmpFileName); res = Path.Combine(Path.GetDirectoryName(res), substr); goto next; } tmpFileNames[jj] = res; } else { tmpFileNames[jj] = tmpFileName; } jj++; } newFileNames = tmpFileNames; pgSetFileNames = ObjectArrayToBStrWrapperArray(newFileNames); //var documentsToRemove = ObjectArrayToBStrWrapperArray(newFileNames.Where(x => x == "C:\\temp").ToArray()); //swPackAndGo.RemoveExternalDocuments(documentsToRemove); status = swPackAndGo.SetDocumentSaveToNames(pgSetFileNames); var statuses = (int[])swModelDocExt.SavePackAndGo(swPackAndGo); //перед открытием создать файлик dictionary string dictFile= Path.Combine(Path.GetDirectoryName(_openFile), Path.GetFileNameWithoutExtension(_openFile) + "_dictionary.txt"); if (File.Exists(dictFile)) File.Delete(dictFile); using (File.CreateText(dictFile)) { }; //File.Create(dictFile); List<string> strArr = new List<string>(); foreach (string file in Directory.GetFiles(partDir, "*.SLDASM", SearchOption.TopDirectoryOnly)) { strArr.Add(file); } File.SetAttributes(dictFile, FileAttributes.Normal); using (System.IO.StreamWriter file = new System.IO.StreamWriter(dictFile, true)) { foreach (var line in strArr) { file.WriteLine(line); } file.Close(); } //File.WriteAllLines(dictFile, strArr); File.SetAttributes(dictFile, FileAttributes.Hidden); //тут проверить что все оторвалось. Если что, поправить ссылки SwDMApplication swDocMgr = SwAddin.GetSwDmApp(); SwDmDocumentOpenError oe; SwDMSearchOption src = swDocMgr.GetSearchOptionObject(); object brokenRefVar; string[] files = Directory.GetFiles(Path.GetDirectoryName(_openFile),"*.*",SearchOption.AllDirectories); foreach (string fileName in files) { SwDMDocument8 swDoc = null; if (fileName.ToLower().Contains("sldasm")) swDoc = (SwDMDocument8) swDocMgr.GetDocument(fileName, SwDmDocumentType.swDmDocumentAssembly, false, out oe); if (swDoc != null) { var varRef = (string[]) swDoc.GetAllExternalReferences2(src, out brokenRefVar); if (varRef != null && varRef.Length != 0) { foreach (string o in varRef) { if (o.ToUpper().Contains("_SWLIB_BACKUP")) { string tt = Path.GetFileNameWithoutExtension(o); string newRef = null; foreach (var fn in files) { if (fn.Contains(tt)) { newRef = fn; break; } } if (newRef != null) { swDoc.ReplaceReference(o, newRef); swDoc.Save(); } } } } else { swDoc.CloseDoc(); continue; } swDoc.CloseDoc(); } } swApp.CloseAllDocuments(true); if (!File.Exists(_openFile)) throw new Exception("Ошибка. Не найден файл: " + _openFile); foreach (var file in newFileNames) { File.SetAttributes(file,FileAttributes.Normal); } //Logging.Log.Instance.Debug("SetAttributes "); SwAddin.IsEventsEnabled = true; swModelDoc = (ModelDoc2)swApp.OpenDoc6(_openFile, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors, warnings); SwAddin.IsEventsEnabled = false; //Logging.Log.Instance.Debug("OpenDoc6"); swModelDoc.EditRebuild3(); swAddin.AttachModelDocEventHandler(swModelDoc); //теперь тут пробежатся по всем файлам в filesToHideAndShow. key -хайдить , value - показывать //foreach (var files in filesToHideAndShow) //{ // if (File.Exists(files.Key) && File.Exists(files.Value)) // { // File.SetAttributes(files.Value, FileAttributes.Normal); // File.SetAttributes(files.Key, FileAttributes.Hidden); // string nextFile,sourceFile = files.Key; // while (SwAddin.IfNextExist(sourceFile, out nextFile)) // { // sourceFile = nextFile; // File.SetAttributes(nextFile, FileAttributes.Hidden); // } // } //} SwDmCustomInfoType swDmCstInfoType; if (Directory.Exists(furnDir)) { foreach (string path in Directory.GetFiles(furnDir, "*.sldasm", SearchOption.TopDirectoryOnly)) { if (!File.Exists(path)) continue; var swDoc = swDocMgr.GetDocument(path, SwDmDocumentType.swDmDocumentAssembly, true, out oe); if (Path.GetFileNameWithoutExtension(path).First() == '~' || swDoc == null) continue; string valueOfName = swDoc.GetCustomProperty("Accessories", out swDmCstInfoType); swDoc.CloseDoc(); if (valueOfName != null && (valueOfName == "No" || valueOfName == "no")) { File.Delete(path); } } } var oComps = (object[])((AssemblyDoc)swModelDoc).GetComponents(true); if (oComps != null) { foreach (var oComp in oComps) { var comp = (Component2)oComp; var model = (ModelDoc2)comp.GetModelDoc(); if (model != null) { File.SetAttributes(model.GetPathName(), FileAttributes.Normal); var swDoc = swDocMgr.GetDocument(model.GetPathName(), SwDmDocumentType.swDmDocumentUnknown, true, out oe); if (swDoc != null) { var names = (string[])swDoc.GetCustomPropertyNames(); try { foreach (var name in names) { string valueOfName = swDoc.GetCustomProperty(name, out swDmCstInfoType); string lowValOfName = valueOfName.ToLower(); if (lowValOfName.Contains("@") && lowValOfName.Contains("#") && (lowValOfName.Contains(".sld"))) { var split = valueOfName.Split('.'); string tmp = split.First(); string ext = split.Last(); if (lowValOfName.Contains("#" + xName) || tmp.ToUpper().Last()!='P') continue; string sid = tmp.Substring(tmp.Length - 3, 2); int id; if (!int.TryParse(sid,out id)) continue; tmp = tmp.Substring(0, tmp.Length - 4); tmp = tmp +" #" +xName+"-"+id +"."+ext; swAddin.SetModelProperty(model, name, "", swCustomInfoType_e. swCustomInfoText, tmp); model.Save(); //swDoc.SetCustomProperty(name, tmp); } } } catch (Exception) { Logging.Log.Instance.Debug("Ошибка при попытке обратится к св-ву. Деталь: " + swDoc.FullName); } finally { swDoc.CloseDoc(); } } } } } Cash.ActualizaAllCash(); SwAddin.IsEventsEnabled = true; linksToCash.Remove(_openFile); //скопировать fpTime.txt string fpTime = Path.Combine(tempDir, "fpTime.txt"); if (File.Exists(fpTime)) File.Copy(fpTime, Path.Combine(Path.GetDirectoryName(_openFile), "fpTime.txt")); CopyDrawings(rFileNames, newFileNames, tempDir, _openFile); CopyProgramms(rFileNames, newFileNames,tempDir, _openFile); } catch(Exception e) { MessageBox.Show(e.Message); return; } finally { WaitTime.Instance.HideWait(); } }