C# WinForm操作Word模板抛出RPC服务器不可用COM异常求助
问题原因
The RPC server is unavailable报错在Office Interop场景下,绝大多数是因为代码逻辑错误导致Word进程意外崩溃退出,后续的COM调用失去了可通信的目标进程才触发的。当前代码里存在多个致命逻辑错误直接触发了该问题:
- 行索引越界:循环遍历
dataGridView1.RowCount时,内部使用了i+1获取行,当i走到最后一行时索引超出范围,直接触发异常导致Word进程未正常退出就被终止 - 遍历逻辑错误:DataGridView两列分别存储「待替换标签」和「替换内容」,每行对应一条规则,不需要嵌套列循环,当前的双层循环逻辑完全不符合规则存储设计
- 单元格取值错误:直接对
DataGridViewCell对象调用ToString()获取到的是单元格类型名称,不是单元格内存储的实际值,会导致Word查找无效内容引发异常 - COM资源未正确释放:操作完成后没有关闭文档、退出Word进程,多次运行后后台会残留大量WINWORD.EXE进程,也会触发RPC调用异常
修复方案
1. 修正核心替换逻辑
替换click_start_Click方法及配套替换方法的代码,修正遍历逻辑,补充资源释放:
private void click_start_Click(object sender, EventArgs e) { Word.Application wordApp = null; Word.Document wordDocument = null; try { string vhod = inputBox.Text.Trim(); string uhod = outputBox.Text.Trim(); // 基础路径校验 if (!File.Exists(vhod)) { MessageBox.Show("输入文件不存在"); return; } if (string.IsNullOrEmpty(uhod)) { MessageBox.Show("输出路径不能为空"); return; } wordApp = new Word.Application(); wordApp.Visible = false; wordDocument = wordApp.Documents.Open(vhod); // 遍历替换规则,每行对应一条规则 foreach (DataGridViewRow row in dataGridView1.Rows) { // 跳过空白新增行 if (row.IsNewRow) continue; // 取值要取Value属性 string stub = row.Cells[0].Value?.ToString().Trim(); string replaceText = row.Cells[1].Value?.ToString().Trim(); // 跳过空规则 if (string.IsNullOrEmpty(stub)) continue; ReplaceWordStub(stub, replaceText, wordDocument); } wordDocument.SaveAs2(uhod); } catch (Exception ex) { MessageBox.Show("操作失败:" + ex.Message); } finally { // 无论成功失败都释放COM资源,避免Word进程残留 if (wordDocument != null) { wordDocument.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDocument); } if (wordApp != null) { wordApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); } } } private void ReplaceWordStub(string stubToReplace, string text, Word.Document wordDocument) { var range = wordDocument.Content; range.Find.ClearFormatting(); // 补充替换参数实现全局替换 range.Find.Execute( FindText: stubToReplace, ReplaceWith: text, Replace: Word.WdReplace.wdReplaceAll); }
2. 额外排查项
如果修改后仍有报错,可以检查以下配置:
- 确认本机已安装完整版Microsoft Office,不要用WPS或者精简版Office,Interop依赖Office的COM组件
- 打开任务管理器,结束所有后台残留的WINWORD.EXE进程后再运行程序
- 输入的Word文件不要是被占用的只读状态,避免打开失败
内容的提问来源于stack exchange,提问作者de_Scharf
相关产品推荐
相关产品推荐

