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

移动含子文件夹的目录失败:游戏Mod管理器遇IO异常求助

解决Directory.Move报错:文件已存在的问题

报错System.IO.IOException: Cannot create a file when that file already exists的核心原因是:Directory.Move方法不允许目标路径存在同名目录,它不会自动覆盖或合并现有内容。

修复方案

  1. 先检查目标路径是否存在同名目录
    在执行移动前,先构造完整的目标路径(包含要移动的目录名称),判断该路径是否已存在。根据需求选择处理方式:

    • 直接删除目标目录(需谨慎,建议添加确认提示)
    • 提示用户手动处理冲突
    • 重命名源目录后再移动
  2. 修改代码示例
    替换原代码中的路径拼接方式,改用Path.Combine确保路径格式正确,同时添加存在性检查:

private void button3_Click(object sender, EventArgs e)
{
    foreach (ListViewItem selecteditem in listView1.SelectedItems)
    {
        if (selecteditem.SubItems[1].Text == "loaded")
        {
            string currentItemPath = selecteditem.SubItems[0].Text;
            string dirName = Path.GetFileName(currentItemPath);
            string fullTargetPath = Path.Combine(MODSOFF, dirName);
            
            // 若目标目录已存在,先删除(可替换为用户提示逻辑)
            if (Directory.Exists(fullTargetPath))
            {
                Directory.Delete(fullTargetPath, true);
            }
            Directory.Move(currentItemPath, fullTargetPath);
            ModChecker();
        }
        else if (selecteditem.SubItems[1].Text == "unloaded")
        {
            string currentItemPath = selecteditem.SubItems[0].Text;
            string dirName = Path.GetFileName(currentItemPath);
            string targetDir = Path.Combine(BRDIR, "BrickRigs", "Mods");
            string fullTargetPath = Path.Combine(targetDir, dirName);
            
            if (Directory.Exists(fullTargetPath))
            {
                Directory.Delete(fullTargetPath, true);
            }
            Directory.Move(currentItemPath, fullTargetPath);
            ModChecker();
        }
    }
}

注意事项

  • 使用Path.Combine替代字符串拼接,避免因路径分隔符(/或\)导致的错误
  • Directory.Delete(fullTargetPath, true)会递归删除目标目录下的所有内容,若需要保留数据,需替换为合并目录的逻辑(遍历文件逐个移动)
  • 建议增加用户交互提示,比如弹窗询问是否覆盖现有Mod,防止误删重要数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 22:12:40