You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何避免foreach循环中重复弹出FolderBrowserDialog

解决方案

问题分析

原代码存在三个核心问题:

  • FolderBrowserDialog 放在foreach循环内部,导致每个选中文件都会触发一次弹窗
  • 循环中执行fileList.Add(file)会引发无限循环(遍历集合时向其中添加元素,导致遍历永远无法结束)
  • 每次循环都创建新的Word应用实例,造成不必要的资源消耗

修改后的代码

// 先弹出一次文件夹选择对话框,获取目标路径
string targetFolder = string.Empty;
FolderBrowserDialog fbd1 = new FolderBrowserDialog();
fbd1.ShowNewFolderButton = true;
if (fbd1.ShowDialog() == DialogResult.OK)
{
    targetFolder = fbd1.SelectedPath;
}
else
{
    // 用户取消选择,直接返回
    return;
}

// 初始化一次Word应用,避免重复创建
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
object o = Missing.Value;
object oFalse = false;
object wordFileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;

try
{
    // 遍历选中的文件(移除原代码中fileList.Add(file)的错误代码)
    foreach(File file in fileList)
    {
        if (file.fileSelection == true && !string.IsNullOrEmpty(file.newFilename))
        {
            // 用Path.Combine拼接路径,避免格式错误
            string savePath = Path.Combine(targetFolder, $"{file.newFilename}.pdf");
            
            // 处理Word文档转换
            Microsoft.Office.Interop.Word.Document wordDoc = wordApp.Documents.Add(ref o);
            // 这里添加原代码中"some code here"的内容(比如向文档写入数据)
            
            wordDoc.SaveAs2(savePath, ref wordFileFormat, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o);
            wordDoc.Close(ref oFalse, ref o, ref o);
        }
    }
}
finally
{
    // 确保Word应用退出,释放资源
    wordApp.Quit(ref o, ref o, ref o);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
}

// 刷新DataGridView
dataGridView1.Refresh();

关键修改点

  • 将文件夹选择逻辑移至循环外部,仅触发一次弹窗
  • 移除fileList.Add(file),避免无限循环
  • 统一创建和释放Word应用实例,优化资源使用
  • 使用Path.Combine()拼接路径,避免手动拼接字符串导致的格式错误
  • 增加用户取消选择文件夹时的退出逻辑,避免后续报错

内容的提问来源于stack exchange,提问作者LFLJM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:10:45