Example #1
0
        public void OpenRelvantFile()
        {
            IModelDoc2 modDoc = (IModelDoc2)iSwApp.ActiveDoc;
            //获取当前打开文件类型:1-part,2-assembly, 3-drawing
            int    modleType = modDoc.GetType();
            string fileName;
            string targetName;
            string readyName;
            string path;

            string[] siblingNames;
            int      errors   = 0;
            int      warnings = 0;

            path         = modDoc.GetPathName().Substring(0, modDoc.GetPathName().LastIndexOf("\\"));
            fileName     = modDoc.GetPathName().Substring(modDoc.GetPathName().LastIndexOf("\\") + 1, modDoc.GetPathName().LastIndexOf(".") - modDoc.GetPathName().LastIndexOf("\\") - 1);
            siblingNames = Directory.GetFiles(path, "*.sld");

            foreach (string x in siblingNames)
            {
                //获取不包括路径的文件名
                readyName = x.ToLower().Replace("~$", "").Substring(x.LastIndexOf("\\") + 1, x.LastIndexOf(".") - x.LastIndexOf("\\") - 1);
                if (x.Replace("~$", "") != modDoc.GetPathName() & (readyName.LastIndexOf(fileName.ToLower()) != -1 || fileName.LastIndexOf(readyName.ToLower()) != -1))
                {
                    targetName = x.Replace("~$", "");
                    iSwApp.OpenDoc6(targetName, 1, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
                    iSwApp.OpenDoc6(targetName, 2, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
                    iSwApp.OpenDoc6(targetName, 3, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
                    iSwApp.ActivateDoc3(x.ToLower().Replace("~$", "").Substring(x.LastIndexOf("\\") + 1, x.Length - x.LastIndexOf("\\") - 1), false, (int)swRebuildOnActivation_e.swUserDecision, ref errors);
                }
            }
        }
Example #2
0
        public void OpenDrawing()
        {
            ModelDoc2 swModel = iSwApp.ActiveDoc;
            //SelectionMgr selMgr = new SelectionMgr();
            int        iErrors   = 0;
            int        iWarnings = 0;
            Component2 swComponent;
            String     swComponentPath;

            SelectionMgr selMgr = default(SelectionMgr);

            selMgr      = (SelectionMgr)swModel.SelectionManager;
            swComponent = selMgr.GetSelectedObjectsComponent4(1, -1);

            try
            {
                swComponentPath = swComponent.GetPathName();
            }
            catch (NullReferenceException)
            {
                swComponentPath = swModel.GetPathName();
                //swComponentPath = swComponent.GetPathName();
            }
            var    swDrawingArr = swComponentPath.Split('.');
            String swDrawPath   = swDrawingArr[0] + ".SLDDRW";

            iSwApp.OpenDoc6(swDrawPath, 3, 1, "", iErrors, iWarnings);

            //MessageBox.Show(swComponentPath.ToString());
        }
Example #3
0
        private IModelDoc2 Open(string fullpath)
        {
            var errors   = 0;
            var warnings = 0;

            return(_sldWorks.OpenDoc6(
                       fullpath,
                       (int)GetDocumentType(fullpath),
                       (int)swOpenDocOptions_e.swOpenDocOptions_Silent,
                       string.Empty,
                       ref errors,
                       ref warnings));
        }
Example #4
0
        public void ExportSketches(ISldWorks swApp)
        {
            string projectFolderPath = Path.GetDirectoryName(((ModelDoc2)swApp.ActiveDoc).GetPathName());

            OracleConnection connection;
            using (connection = new OracleConnection(ConnectionString))
            {
                using (OracleCommand cmd = new OracleCommand())
                {
                    cmd.Connection = connection;
                    connection.Open();
                    cmd.CommandText = "GENERAL.SWR_FILEDATA_SKETCHES_PRE_SW";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("P_NUMAGREE", OracleDbType.Varchar2).Value = OrderNumber;
                    cmd.Parameters.Add("P_COMMIT", OracleDbType.Char).Value = 'T';
                    cmd.ExecuteNonQuery();
                }

                using (OracleCommand cmd = new OracleCommand())
                {
                    cmd.Connection = connection;

                    string commandText = @"SELECT  SWRFDS.IT,
                                                    SWRFDS.ITAGREEMENT,
                                                    SWRFDS.FILEPATH,
                                                    SWRFDS.FILENAME,
                                                    SWRFDS.IDSKETCH,
                                                    SWRFDS.FILENAME_DRW,
                                                    SWRFDS.FILENAME_DWG,
                                                    SWRFDS.FILENAME_PDF,
                                                    SWRFDS.FILENAME_XML,
                                                    SWRFDS.DWG_SKETCH,
                                                    SWRFDS.PDF_SKETCH,
                                                    SWRFDS.XML_SKETCH,
                                                    SWRFDS.CODEFILETYPE
                                            FROM GENERAL.VW_SWR_FILEDATA_SKETCHES SWRFDS
                                            WHERE SWRFDS.ITAGREEMENT = SCENTRE.AGR_GETITAGREE(:P_NUMAGREE)";

                    cmd.CommandText = commandText;
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("P_NUMAGREE", OracleDbType.Varchar2).Value = OrderNumber;

                    OracleDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        int it = (int)reader["IT"];
                        string filePath = reader["FILEPATH"].ToString();
                        string fileName = reader["FILENAME"].ToString();
                        string fileName_DRW = reader["FILENAME_DRW"].ToString();
                        string fileName_DWG = reader["FILENAME_DWG"].ToString();
                        string fileNamePDF = reader["FILENAME_PDF"].ToString();
                        string fileName_XML = reader["FILENAME_XML"].ToString();

                        if (File.Exists(filePath + fileName_DRW))
                        {
                            //открываем файл в солиде
                            int errors = 0;
                            int warnings = 0;
                            ModelDoc2 drwModel = swApp.OpenDoc6(filePath + fileName_DRW, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, string.Empty, errors, warnings);

                            //сохраняем в dwg
                            object exportData = null;
                            string dwgFilePath = filePath + fileName_DWG;
                            drwModel.Extension.SaveAs(dwgFilePath, 0, 0, exportData, errors, warnings);

                            //сохраняем в pdf
                            /*/
                            exportData = swApp.GetExportFileData(1);
                            string pdfFilePath = projectFolderPath + @"\\ЧЕРТЕЖИ_PDF\\" + fileNamePDF;
                            if (!Directory.Exists(projectFolderPath + @"\\ЧЕРТЕЖИ_PDF\\"))
                                Directory.CreateDirectory(projectFolderPath + @"\\ЧЕРТЕЖИ_PDF\\");
                            drwModel.Extension.SaveAs(pdfFilePath, 0, 0, exportData, errors, warnings);
                            /*/

                            //закрываем файл в солиде
                            swApp.QuitDoc(drwModel.GetTitle());

                            //архивируем dwg и pdf
                            string dwgZipFilePath = fileToZip(dwgFilePath);
                            //string pdfZipFilePath = fileToZip(pdfFilePath);

                            //отправляем dwg.zip в базу
                            byte[] dwgZipFile = File.ReadAllBytes(dwgZipFilePath);
                            using (OracleCommand cmdSendDwg = new OracleCommand())
                            {
                                cmdSendDwg.Connection = connection;
                                cmdSendDwg.CommandText = "GENERAL.SWR_FILEDATA_SKTDWG_UPD";
                                cmdSendDwg.CommandType = CommandType.StoredProcedure;
                                cmdSendDwg.Parameters.Add("P_IT", OracleDbType.Int32).Value = it;
                                cmdSendDwg.Parameters.Add("P_FILENAME_DWG", OracleDbType.Varchar2).Value = Path.GetFileName(dwgZipFilePath);
                                cmdSendDwg.Parameters.Add("P_DWG_SKETCH", OracleDbType.Blob).Value = dwgZipFile;
                                cmdSendDwg.Parameters.Add("P_COMMIT", OracleDbType.Char).Value = 'T';
                                cmdSendDwg.ExecuteNonQuery();
                            }

                            //отправляем pdf.zip в базу
                            /*/
                            byte[] pdfZipFile = File.ReadAllBytes(pdfZipFilePath);
                            using (OracleCommand cmdSendPdf = new OracleCommand())
                            {
                                cmdSendPdf.Connection = connection;
                                cmdSendPdf.CommandText = "GENERAL.SWR_FILEDATA_SKTPDF_UPD";
                                cmdSendPdf.CommandType = CommandType.StoredProcedure;
                                cmdSendPdf.Parameters.Add("P_IT", OracleDbType.Int32).Value = it;
                                cmdSendPdf.Parameters.Add("P_FILENAME_PDF", OracleDbType.Varchar2).Value = Path.GetFileName(pdfZipFilePath);
                                cmdSendPdf.Parameters.Add("P_PDF_SKETCH", OracleDbType.Blob).Value = pdfZipFile;
                                cmdSendPdf.Parameters.Add("P_COMMIT", OracleDbType.Char).Value = 'T';
                                cmdSendPdf.ExecuteNonQuery();
                            }
                            /*/

                            //отправляем xml в базу
                            string xmlFilePath = projectFolderPath + @"\Программы\" + fileName_XML;
                            if (File.Exists(xmlFilePath))
                            {
                                byte[] xmlFile = File.ReadAllBytes(xmlFilePath);
                                using (OracleCommand cmdSendXml = new OracleCommand())
                                {
                                    cmdSendXml.Connection = connection;
                                    cmdSendXml.CommandText = "GENERAL.SWR_FILEDATA_SKTXML_UPD";
                                    cmdSendXml.CommandType = CommandType.StoredProcedure;
                                    cmdSendXml.Parameters.Add("P_IT", OracleDbType.Int32).Value = it;
                                    cmdSendXml.Parameters.Add("P_FILENAME_XML", OracleDbType.Varchar2).Value = Path.GetFileName(xmlFilePath);
                                    cmdSendXml.Parameters.Add("P_XML_SKETCH", OracleDbType.Blob).Value = xmlFile;
                                    cmdSendXml.Parameters.Add("P_COMMIT", OracleDbType.Char).Value = 'T';
                                    cmdSendXml.ExecuteNonQuery();
                                }
                            }

                            //удаляем архив dwg.zip и сами файлы dwg
                            File.Delete(dwgFilePath);
                            File.Delete(dwgZipFilePath);

                            //удаляем архив pdf.zip
                            //File.Delete(pdfZipFilePath);
                        }
                        else
                            throw new FileNotFoundException("Не найден файл чертежа " + filePath + fileName_DRW);
                    }
                    //удаляем папку ЧЕРТЕЖИ_PDF
                    //Directory.Delete(projectFolderPath + @"\\ЧЕРТЕЖИ_PDF\\");
                }
            }
        }
Example #5
0
        /// <summary>
        /// Add componect to active doc
        /// </summary>
        void AddComponectToActiveDoc(string partFileName)
        {
            ModelDocExtension swDocExt;
            AssemblyDoc       swAssy;
            string            tmpPath;
            ModelDoc2         tmpObj;
            bool          boolstat;
            Component2    swcomponent;
            Feature       matefeature;
            string        MateName;
            string        FirstSelection;
            string        SecondSelection;
            swMateAlign_e Alignment;
            string        strCompName;
            string        AssemblyTitle;
            string        AssemblyName;
            int           errors   = 0;
            int           warnings = 0;
            int           mateError;

            // Get title of assembly document
            AssemblyTitle = pDoc.GetTitle();

            // Split the title into two strings using the period (.) as the delimiter
            string[] strings = AssemblyTitle.Split(new Char[] { '.' });

            // Use AssemblyName when mating the component with the assembly
            AssemblyName = (string)strings[0];


            boolstat = true;

            string strCompModelname = null;

            strCompModelname = partFileName;

            // Because the component resides in the same folder as the assembly, get
            // the assembly's path, strip out the assembly filename, concatenate
            // the rest of the path to the component filename, and use this string to
            // open the component
            tmpPath = pDoc.GetPathName();
            //int idx;
            //idx = tmpPath.LastIndexOf(AssemblyTitle);
            string compPath;

            //tmpPath = tmpPath.Substring(0, (idx));
            //compPath = string.Concat(tmpPath, strCompModelname);
            compPath = strCompModelname;

            // Open the component
            tmpObj = (ModelDoc2)swApp.OpenDoc6(compPath, (int)swDocumentTypes_e.swDocPART, 0, "", ref errors, ref warnings);

            // Check to see if the file is read-only or cannot be found; display error
            // messages if either
            if (warnings == (int)swFileLoadWarning_e.swFileLoadWarning_ReadOnly)
            {
                MessageBox.Show("This file is read-only.");
                boolstat = false;
            }

            if (tmpObj == null)
            {
                MessageBox.Show("Cannot locate the file.");
                boolstat = false;
            }

            //Re-activate the assembly so that you can add the component to it
            pDoc   = (ModelDoc2)swApp.ActivateDoc2(AssemblyTitle, true, ref errors);
            swAssy = (AssemblyDoc)pDoc;


            // Add the component to the assembly document.
            // Currently only one option,
            // swAddComponentConfigOptions_e.swAddComponentConfigOptions_CurrentSelectedConfig,
            // works for adding a part using AddComponent5

            // The other options,
            // swAddComponentConfigOptions_e.swAddComponentConfigOptions_NewConfigWithAllReferenceModels
            // and swAddComponentConfigOptions_e.swAddComponentConfigOptions_NewConfigWithAsmStructure,
            // work only for adding assemblies using AddComponent5
            swcomponent = (Component2)swAssy.AddComponent5(strCompModelname, (int)swAddComponentConfigOptions_e.swAddComponentConfigOptions_CurrentSelectedConfig, "", false, "", -1, -1, -1);

            // Get the name of the component for the mate
            strCompName = swcomponent.Name2;

            // Create the name of the mate and the names of the planes to use for the mate
            MateName        = "top_coinc_" + strCompName;
            FirstSelection  = "Top@" + strCompName + "@" + AssemblyName;
            SecondSelection = "Front@" + AssemblyName;
            swDocExt        = (ModelDocExtension)pDoc.Extension;
            pDoc.ClearSelection2(true);

            // Select the planes for the mate
            boolstat = swDocExt.SelectByID2(FirstSelection, "PLANE", 0, 0, 0, true, 1, null, (int)swSelectOption_e.swSelectOptionDefault);
            boolstat = swDocExt.SelectByID2(SecondSelection, "PLANE", 0, 0, 0, true, 1, null, (int)swSelectOption_e.swSelectOptionDefault);

            // Add the mate
            matefeature = (Feature)swAssy.AddMate3((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0,
                                                   0, false, out mateError);
            matefeature.Name = MateName;

            pDoc.ViewZoomtofit2();
        }
Example #6
0
        public void GetXML()
        {
            //iSwApp.CommandInProgress = true;
            ModelDoc2   swModel;
            AssemblyDoc swAssy;
            List <Comp> coll;
            XDocument   doc;
            XElement    xml, transaction, project, configurations, configuration, documents, components, component;

            int           errors   = 0;
            int           warnings = 0;
            string        fileName; // GetOpenFileName
            string        path;
            List <string> conf;

            string[] сonfNames;
            swModel = (ModelDoc2)iSwApp.ActiveDoc;
            if (swModel == null)
            {
                fileName = iSwApp.GetOpenFileName("Выберите сборку", "", "SLDASM Files (*.SLDASM)|*.SLDASM|", out _, out _, out _);
                //Проверяем путь
                if (fileName == "")
                {
                    return;
                }
                swModel = (ModelDoc2)iSwApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            }

            //Проверяем открыта сборка или нет
            if ((swModel.GetType() != 2) | (swModel == null))
            {
                iSwApp.SendMsgToUser2("Откройте сборку", 4, 2);
                return;
            }

            //iSwApp.UnloadAddIn(sAddinName);
            fileName       = swModel.GetPathName();
            doc            = new XDocument(new XDeclaration("1.0", "Windows-1251", "Yes"));
            xml            = new XElement("xml");
            transaction    = new XElement("transaction", new XAttribute("Type", "SOLIDWORKS"), new XAttribute("version", "1.2"), new XAttribute("Date", DateTime.Now.ToString("d")), new XAttribute("Time", DateTime.Now.ToString("T")));
            project        = new XElement("project", new XAttribute("Project_Path", fileName), new XAttribute("Project_Name", swModel.GetTitle() + ".SldAsm"));
            configurations = new XElement("configurations");
            сonfNames      = (string[])swModel.GetConfigurationNames();
            conf           = new List <string>(сonfNames);
            conf.Sort();
            ConfigForm f = new ConfigForm(conf);

            f.ShowDialog();
            if (f.conf == null)
            {
                return;
            }

            if (f.conf.Count == 0)
            {
                return;
            }
            iSwApp.UnloadAddIn(sAddinName);
            f.conf.Sort();
            for (int i = 0; i < f.conf.Count; i++)
            {
                swModel.ShowConfiguration2(f.conf[i]);
                swAssy        = (AssemblyDoc)swModel;
                configuration = new XElement("configuration", new XAttribute("name", f.conf[i]));
                coll          = Comp.GetColl((SldWorks)iSwApp);
                //iSwApp.SendMsgToUser2("Всего " + coll.Count, 2, 2);
                documents  = Comp.GetDocuments(swAssy);
                components = new XElement("components");
                foreach (Comp k in coll)
                {
                    component = Comp.GetComponent(k);
                    components.Add(component);
                }
                if (i == 0)
                {
                    configuration.Add(Comp.GetGraphs(swAssy));
                }
                configuration.Add(documents);
                configuration.Add(components);
                configurations.Add(configuration);
                //swModel.ShowConfiguration2(f.conf[0]);
            }

            project.Add(configurations);
            transaction.Add(project);
            xml.Add(transaction);
            doc.Add(xml);
            path = fileName.Substring(0, fileName.Length - 7) + ".xml";
            //iSwApp.SendMsgToUser2(path, 4, 2);
            iSwApp.LoadAddIn(sAddinName);
            doc.Save(path);
            //iSwApp.CommandInProgress = false;
        }
Example #7
0
        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();

            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="partsname"></param>
        private void CreateNewAssembly(string assemblyName, List <string> partsname)
        {
            string assemblyDefaultPath = iswApp.GetDocumentTemplate(2, "", 0, 0, 0);

            var part = iswApp.NewDocument(assemblyDefaultPath, 0, 0, 0);

            if (part != null)
            {
                AssemblyDoc assemblyDoc = part as AssemblyDoc;

                ModelDoc2 modelDoc2 = assemblyDoc as ModelDoc2;

                ModelDocExtension swModExt = default(ModelDocExtension);

                int errors   = 0;
                int warnings = 0;

                swModExt = (ModelDocExtension)modelDoc2.Extension;

                swModExt.SaveAs(assemblyName,
                                (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, errors, warnings);

                modelDoc2 = (ModelDoc2)iswApp.ActiveDoc;

                int i     = 0;
                int tempV = ProgressBar.Value;
                foreach (var partN in partsname)
                {
                    labStatus.Text = "正在装配-->" + Path.GetFileNameWithoutExtension(partN);

                    ProgressBar.Value = tempV + i;

                    iswApp.OpenDoc6(partN.ToString(), 1, 32, "", ref errors, ref warnings);

                    assemblyDoc = (AssemblyDoc)iswApp.ActivateDoc3(System.IO.Path.GetFileNameWithoutExtension(assemblyName) + ".sldasm", true, 0, errors);

                    Component2 swInsertedComponent = default(Component2);

                    swInsertedComponent = assemblyDoc.AddComponent5(partN, 0, "", false, "", 0, 0, 0);

                    modelDoc2 = (ModelDoc2)iswApp.ActiveDoc;
                    modelDoc2.ClearSelection2(true);

                    modelDoc2.Extension.SelectByID2(swInsertedComponent.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0);

                    assemblyDoc.UnfixComponent();

                    modelDoc2.ClearSelection2(true);

                    modelDoc2.Extension.SelectByID2("Point1@Origin@" + swInsertedComponent.GetSelectByIDString(), "EXTSKETCHPOINT", 0, 0, 0, false, 0, null, 0);

                    modelDoc2.Extension.SelectByID2("Point1@Origin", "EXTSKETCHPOINT", 0, 0, 0, true, 0, null, 0);

                    Mate2 mate2 = default(Mate2);

                    mate2 = assemblyDoc.AddMate5(20, -1, false, 0, 0, 0, 0, 0.001, 0, 0, 0, false, false, 0, out int warings);
                    modelDoc2.ClearSelection2(true);
                    modelDoc2.EditRebuild3();

                    iswApp.CloseDoc(partN);

                    i = i + 1;
                }

                iswApp.ActivateDoc3(System.IO.Path.GetFileNameWithoutExtension(assemblyName) + ".sldasm", true, 0, errors);
                modelDoc2 = (ModelDoc2)iswApp.ActiveDoc;
                modelDoc2.ShowNamedView2("*等轴测", 7);
                modelDoc2.ViewZoomtofit2();
                modelDoc2.Save();
            }

            ProgressBar.Value = ProgressBar.Maximum;
        }