news 2026/5/25 23:47:37

solidworks导出step c#

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
solidworks导出step c#

https://help.solidworks.com/2023/english/api/swconst/filesaveasstepoptions.htm


privatevoidImportSelectedStepBatchSldprt(){try{StartCancelableCommand();if(swApp==null){Debug.WriteLine("SolidWorks 未初始化");return;}string[]selectedPaths;using(vardlg=newOpenFileDialog()){dlg.Title="选择要导入为 SLDPRT 的 STEP 文件";dlg.Filter="STEP 文件 (*.step;*.stp)|*.step;*.stp|所有文件 (*.*)|*.*";dlg.Multiselect=true;dlg.CheckFileExists=true;if(dlg.ShowDialog()!=DialogResult.OK){return;}selectedPaths=dlg.FileNames;}string[]stepPaths=selectedPaths.Where(p=>!string.IsNullOrWhiteSpace(p)&&step2one.IsStepFilePath(p)&&File.Exists(p)).Select(Path.GetFullPath).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();if(stepPaths.Length==0){swApp.SendMsgToUser("未选择有效的 STEP 文件(.step / .stp)。");return;}intexported=0;intfailed=0;boolprevCommandInProgress=swApp.CommandInProgress;swApp.CommandInProgress=true;try{foreach(stringstepPathinstepPaths){CommandCancelManager.ThrowIfCancellationRequested();intrc=step2one.RunFromStepPath(swApp,stepPath);if(rc>0){exported++;}else{failed++;}}}finally{swApp.CommandInProgress=prevCommandInProgress;}stringmsg=$"SLDPRT 导入完成:成功{exported}个,失败{failed}个。";swApp.SendMsgToUser(msg);Debug.WriteLine(msg);}catch(OperationCanceledException){swApp?.SendMsgToUser("命令已中止");}catch(Exceptionex){Debug.WriteLine($"所选 STEP 批量导入 SLDPRT 失败:{ex.Message}");swApp?.SendMsgToUser($"所选 STEP 批量导入 SLDPRT 失败:{ex.Message}");}}
namespacetools;usingSolidWorks.Interop.sldworks;usingSolidWorks.Interop.swconst;usingSystem.Diagnostics;publicstaticclassstep2one{/// <summary>/// STEP 所在目录下「sldprt」子文件夹内的 SLDPRT 路径(与所选 STEP 批量导入命令一致)。/// </summary>publicstaticstring?GetSldprtOutputPathInSldprtSubfolder(string?stepFullPath){if(string.IsNullOrWhiteSpace(stepFullPath)||!IsStepFilePath(stepFullPath)){returnnull;}stringfullPath=stepFullPath.Trim();string?currentDirectory=Path.GetDirectoryName(fullPath);if(string.IsNullOrWhiteSpace(currentDirectory)){returnnull;}stringpartname=Path.GetFileNameWithoutExtension(fullPath);returnPath.Combine(currentDirectory,"sldprt",$"{partname}.sldprt");}/// <summary>/// 打开 STEP 并另存为所在目录下「sldprt」子文件夹内的 SLDPRT。/// </summary>publicstaticintRunFromStepPath(SldWorksswApp,stringstepFullPath){if(swApp==null){Console.WriteLine("错误:SolidWorks 未初始化。");return0;}string?outputPath=GetSldprtOutputPathInSldprtSubfolder(stepFullPath);if(string.IsNullOrWhiteSpace(outputPath)){Console.WriteLine("错误:无法解析 SLDPRT 输出路径。");return0;}string?outputDirectory=Path.GetDirectoryName(outputPath);if(string.IsNullOrWhiteSpace(outputDirectory)){Console.WriteLine("错误:无法解析 SLDPRT 输出目录。");return0;}if(!Directory.Exists(outputDirectory)){Directory.CreateDirectory(outputDirectory);}stringstepPath=Path.GetFullPath(stepFullPath);if(!File.Exists(stepPath)){Console.WriteLine($"错误:STEP 文件不存在:{stepPath}");return0;}ModelDoc2?partDoc=swApp.GetOpenDocumentByName(stepPath)asModelDoc2;boolopenedHere=false;if(partDoc==null){if(!TryOpenStepFile(swApp,stepPath,outpartDoc,outstring?openError)){Console.WriteLine($"错误:无法打开 STEP 文件:{stepPath}{openError})");return0;}openedHere=true;}if(!TrySaveImportedDocAsSldprt(partDoc,outputPath,outstring?saveError,outintsaveCode)){Console.WriteLine($"错误:STEP 已打开但另存 SLDPRT 失败:{outputPath}{saveError},code={saveCode})");if(openedHere){stringcloseHintPath=partDoc.GetPathName()?.Trim();if(string.IsNullOrEmpty(closeHintPath)){closeHintPath=stepPath;}fast_document_close.CloseWithoutSave(swApp,partDoc,closeHintPath);}return0;}Console.WriteLine($"{saveCode},已导出 SLDPRT 文件到:{outputPath}");if(openedHere){stringcloseHintPath=partDoc.GetPathName()?.Trim();if(string.IsNullOrEmpty(closeHintPath)){closeHintPath=outputPath;}fast_document_close.CloseWithoutSave(swApp,partDoc,closeHintPath);}return1;}privatestaticboolTryOpenStepFile(SldWorksswApp,stringstepFullPath,outModelDoc2?partDoc,outstring?errorMessage){partDoc=null;errorMessage=null;boolhad3DInterconnectPref=TryGet3DInterconnectEnabled(swApp,outboolprev3DInterconnect);if(had3DInterconnectPref){TrySet3DInterconnectEnabled(swApp,false);}try{// 官方示例:GetImportFileData 须传入 STEP 完整路径,而非 "step" 字符串。try{object?importData=swApp.GetImportFileData(stepFullPath);if(importDataisImportStepDatastepImportData){stepImportData.MapConfigurationData=true;intloadErrors=0;partDoc=swApp.LoadFile4(stepFullPath,"r",stepImportData,refloadErrors)asModelDoc2;if(partDoc!=null){returntrue;}errorMessage=$"LoadFile4 失败,errors={loadErrors}";Debug.WriteLine($"LoadFile4 STEP 失败:{stepFullPath}, errors={loadErrors}");}elseif(importData!=null){intloadErrors=0;partDoc=swApp.LoadFile4(stepFullPath,"r",importData,refloadErrors)asModelDoc2;if(partDoc!=null){returntrue;}errorMessage=$"LoadFile4 失败(非 ImportStepData),errors={loadErrors}";}else{errorMessage="GetImportFileData 返回空";}}catch(Exceptionex){errorMessage=$"LoadFile4 异常:{ex.Message}";Debug.WriteLine($"LoadFile4 STEP 异常:{stepFullPath},{ex.Message}");}intopenErrors=0;intopenWarnings=0;partDoc=swApp.OpenDoc6(stepFullPath,(int)swDocumentTypes_e.swDocPART,(int)swOpenDocOptions_e.swOpenDocOptions_Silent,"",refopenErrors,refopenWarnings)asModelDoc2;if(partDoc!=null){errorMessage=null;returntrue;}stringfallback=$"OpenDoc6 失败,errors={openErrors}, warnings={openWarnings}";errorMessage=string.IsNullOrEmpty(errorMessage)?fallback:$"{errorMessage};{fallback}";returnfalse;}finally{if(had3DInterconnectPref){TrySet3DInterconnectEnabled(swApp,prev3DInterconnect);}}}privatestaticboolTrySaveImportedDocAsSldprt(ModelDoc2partDoc,stringoutputPath,outstring?errorMessage,outintsaveCode){errorMessage=null;saveCode=0;TryBreak3DInterconnectLinks(partDoc);intsaveErrors=0;intsaveWarnings=0;boolsaveOk=partDoc.Extension.SaveAs(outputPath,(int)swSaveAsVersion_e.swSaveAsCurrentVersion,(int)swSaveAsOptions_e.swSaveAsOptions_Silent,null,refsaveErrors,refsaveWarnings);saveCode=saveErrors;if(saveOk&&saveErrors==0&&File.Exists(outputPath)){returntrue;}if(File.Exists(outputPath)){returntrue;}saveCode=partDoc.SaveAs3(outputPath,0,(int)swSaveAsOptions_e.swSaveAsOptions_Silent);if(File.Exists(outputPath)){returntrue;}errorMessage=$"Extension.SaveAs 返回{saveOk}, errors={saveErrors}, warnings={saveWarnings}; SaveAs3={saveCode}(32=格式不可用,多为 3D Interconnect 链接文档)";returnfalse;}privatestaticvoidTryBreak3DInterconnectLinks(ModelDoc2doc){Feature?feat=doc.FirstFeature()asFeature;while(feat!=null){try{if(feat.Is3DInterconnectFeature){feat.BreakLink(false,false);}}catch(Exceptionex){Debug.WriteLine($"BreakLink 失败:{feat.Name},{ex.Message}");}feat=feat.GetNextFeature()asFeature;}}privatestaticboolTryGet3DInterconnectEnabled(SldWorksswApp,outboolenabled){enabled=false;try{enabled=swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swMultiCAD_Enable3DInterconnect);returntrue;}catch(Exceptionex){Debug.WriteLine($"读取 3D Interconnect 首选项失败:{ex.Message}");returnfalse;}}privatestaticvoidTrySet3DInterconnectEnabled(SldWorksswApp,boolenabled){try{swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swMultiCAD_Enable3DInterconnect,enabled);}catch(Exceptionex){Debug.WriteLine($"设置 3D Interconnect 首选项失败:{ex.Message}");}}publicstaticboolIsStepFilePath(stringpath){if(string.IsNullOrWhiteSpace(path)){returnfalse;}stringext=Path.GetExtension(path);returnext.Equals(".step",StringComparison.OrdinalIgnoreCase)||ext.Equals(".stp",StringComparison.OrdinalIgnoreCase);}}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/25 23:46:04

基于扩散模型的电网故障智能生成:从N-1筛选到主动风险预测

1. 项目概述&#xff1a;当扩散模型遇见电网安全在电力系统这个庞大而精密的“生命体”中&#xff0c;安全稳定运行是永恒的命题。作为一名长期与电网调度、安全分析打交道的工程师&#xff0c;我深知“故障筛选”这项工作的分量。它就像是电网的“体检医生”&#xff0c;需要在…

作者头像 李华
网站建设 2026/5/25 23:45:55

什么是X402

x402 是最近 Web3 AI Agent&#xff08;AI 智能体&#xff09;领域非常火的一个协议。 你可以把它理解成&#xff1a; “让 AI 和 API 能自动付款的 HTTP 支付协议。” 它的核心目标&#xff1a; 让互联网本身直接支持支付。 一、先理解“402”是什么 互联网里每次访问网站&a…

作者头像 李华
网站建设 2026/5/25 23:44:58

基于ESP32与MQTT的家庭环境监测系统:从传感器选型到数据可视化实战

1. 项目概述与核心价值最近几年&#xff0c;我身边越来越多的朋友开始关注家里的空气质量、温湿度这些看不见摸不着&#xff0c;但又实实在在影响生活舒适度和健康的环境指标。从新装修的房子担心甲醛&#xff0c;到有老人小孩的家庭在意PM2.5和二氧化碳浓度&#xff0c;再到南…

作者头像 李华
网站建设 2026/5/25 23:44:15

“烟雾飘散方向不对”是Prompt问题还是模型缺陷?2024 Q2 Midjourney烟雾物理引擎更新深度逆向分析(含3大未公开--stylize影响因子)

更多请点击&#xff1a; https://kaifayun.com 第一章&#xff1a;烟雾物理引擎的底层架构与设计哲学 烟雾物理引擎并非传统刚体或流体模拟的简单延伸&#xff0c;而是一种面向视觉真实感与实时交互双重目标的轻量级粒子场耦合系统。其设计哲学根植于“可预测的混沌”——在保…

作者头像 李华
网站建设 2026/5/25 23:40:37

教育机构搭建AI编程辅导平台时如何通过Taotoken管理多学员用量

&#x1f680; 告别海外账号与网络限制&#xff01;稳定直连全球优质大模型&#xff0c;限时半价接入中。 &#x1f449; 点击领取海量免费额度 教育机构搭建AI编程辅导平台时如何通过Taotoken管理多学员用量 在构建面向学员的AI编程辅导平台时&#xff0c;教育科技团队面临一…

作者头像 李华