导入"E:\code\试验\装配体导出\装配体3.SLDASM"到当前装配体

正在查看装配体导入相关实现,并通过 SolidWorks 插件桥执行导入。

{
“success”: true,
“message”: “pong”
}
桥已连通。正在确认 insert_assembly_component 的参数格式并执行导入。

{
“success”: true,
“message”: “ok”,
“assemblyPath”: “E:\code\试验\a.SLDASM”
}
当前活动装配体为 E:\code\试验\a.SLDASM,正在插入子装配体。

"message":  "已插入:装配体3-1",
"assemblyPath":  "E:\\code\\试验\\a.SLDASM",
"insertedComponentName":  "装配体3-1",
"insertedComponentPath":  "E:\\code\\试验\\装配体导出\\装配体3.SLDASM"

}
已成功将子装配体导入当前装配体。

结果:

目标装配体: E:\code\试验\a.SLDASM
插入文件: E:\code\试验\装配体导出\装配体3.SLDASM
特征树实例名: 装配体3-1
插入位置: 原点 (0, 0, 0)
装配体已重建并保存。请在 SolidWorks 中查看特征树确认 装配体3-1 是否显示正确;如需指定插入位置或配合关系,告诉我即可

using System;
using System.Diagnostics;
using System.IO;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;

namespace SolidWorksAddinStudy.Services
{
    /// <summary>
    /// 向已打开装配体插入零件或子装配体(供 HTTP / Cursor 桥接)。
    /// </summary>
    public static class AssemblyInsertComponentService
    {
        public static bool TryInsert(
            SldWorks swApp,
            ModelDoc2 assemblyModel,
            string componentFilePath,
            double x,
            double y,
            double z,
            out string insertedComponentName,
            out string insertedComponentPath,
            out string errorMessage)
        {
            insertedComponentName = string.Empty;
            insertedComponentPath = string.Empty;
            errorMessage = string.Empty;

            if (swApp == null)
            {
                errorMessage = "SolidWorks 未连接";
                return false;
            }

            if (assemblyModel == null || assemblyModel.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY)
            {
                errorMessage = "目标文档不是装配体";
                return false;
            }

            string path = (componentFilePath ?? string.Empty).Trim();
            if (path.Length == 0)
            {
                errorMessage = "componentPath 不能为空";
                return false;
            }

            if (!File.Exists(path))
            {
                errorMessage = $"文件不存在: {path}";
                return false;
            }

            string ext = Path.GetExtension(path);
            if (!ext.Equals(".sldprt", StringComparison.OrdinalIgnoreCase)
                && !ext.Equals(".sldasm", StringComparison.OrdinalIgnoreCase))
            {
                errorMessage = "仅支持插入 .sldprt 或 .sldasm";
                return false;
            }

            string asmPath = assemblyModel.GetPathName()?.Trim() ?? string.Empty;
            if (asmPath.Length == 0)
            {
                errorMessage = "请先保存装配体文件";
                return false;
            }

            try
            {
                string activePath = ((ModelDoc2)swApp.ActiveDoc)?.GetPathName()?.Trim() ?? string.Empty;
                if (!string.Equals(activePath, asmPath, StringComparison.OrdinalIgnoreCase))
                {
                    int err = 0;
                    string title = assemblyModel.GetTitle() ?? string.Empty;
                    if (title.Length > 0)
                    {
                        swApp.ActivateDoc3(
                            title,
                            true,
                            (int)swRebuildOnActivation_e.swDontRebuildActiveDoc,
                            ref err);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"AssemblyInsertComponentService activate: {ex.Message}");
            }

            try
            {
                path = Path.GetFullPath(path);

                int docType = ext.Equals(".sldasm", StringComparison.OrdinalIgnoreCase)
                    ? (int)swDocumentTypes_e.swDocASSEMBLY
                    : (int)swDocumentTypes_e.swDocPART;

                bool prevCommandInProgress = swApp.CommandInProgress;
                swApp.CommandInProgress = true;
                try
                {
                    ModelDoc2? componentDoc = swApp.GetOpenDocumentByName(path) as ModelDoc2;
                    bool openedHere = false;
                    if (componentDoc == null)
                    {
                        int openErrors = 0;
                        int openWarnings = 0;
                        componentDoc = swApp.OpenDoc6(
                            path,
                            docType,
                            (int)swOpenDocOptions_e.swOpenDocOptions_Silent,
                            string.Empty,
                            ref openErrors,
                            ref openWarnings) as ModelDoc2;
                        openedHere = componentDoc != null;
                        if (componentDoc == null)
                        {
                            errorMessage = $"无法打开待插入文件(errors={openErrors}, warnings={openWarnings}): {path}";
                            return false;
                        }
                    }

                    string activePathAfterOpen = ((ModelDoc2)swApp.ActiveDoc)?.GetPathName()?.Trim() ?? string.Empty;
                    if (!string.Equals(activePathAfterOpen, asmPath, StringComparison.OrdinalIgnoreCase))
                    {
                        int err = 0;
                        string title = assemblyModel.GetTitle() ?? string.Empty;
                        if (title.Length > 0)
                        {
                            swApp.ActivateDoc3(
                                title,
                                true,
                                (int)swRebuildOnActivation_e.swDontRebuildActiveDoc,
                                ref err);
                        }

                        assemblyModel = (ModelDoc2)swApp.ActiveDoc;
                        if (assemblyModel == null || assemblyModel.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY)
                        {
                            errorMessage = "重新激活目标装配体失败";
                            return false;
                        }
                    }

                    var assemblyDoc = (AssemblyDoc)assemblyModel;
                    Component2? component = assemblyDoc.AddComponent5(
                        path,
                        1,
                        string.Empty,
                        false,
                        string.Empty,
                        x,
                        y,
                        z);
                    if (component == null)
                    {
                        component = assemblyDoc.AddComponent5(
                            path,
                            0,
                            string.Empty,
                            false,
                            string.Empty,
                            x,
                            y,
                            z);
                    }

                    if (component == null)
                    {
                        errorMessage = $"AddComponent5 失败: {path}";
                        return false;
                    }

                    insertedComponentName = component.Name2 ?? component.Name ?? Path.GetFileNameWithoutExtension(path);
                    insertedComponentPath = path;

                    assemblyModel.ClearSelection2(true);
                    component.Select4(false, null, false);
                    assemblyModel.ShowNamedView2("*Isometric", (int)swStandardViews_e.swIsometricView);
                    assemblyModel.ViewZoomtofit2();

                    int errors = 0;
                    int warnings = 0;
                    assemblyModel.EditRebuild3();
                    assemblyModel.Save3((int)swSaveAsOptions_e.swSaveAsOptions_Silent, ref errors, ref warnings);

                    return true;
                }
                finally
                {
                    swApp.CommandInProgress = prevCommandInProgress;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"AssemblyInsertComponentService.TryInsert: {ex}");
                errorMessage = ex.Message;
                return false;
            }
        }
    }
}

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐