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

如何在Main函数返回前调用函数清理临时克隆仓库

实现程序退出时删除临时克隆仓库的几种方法

方法一:使用finally块(推荐简单场景)

finally块会在try代码块执行完毕后无论是否发生异常都执行,刚好适合确保临时目录在Main函数结束时被清理。你需要把临时路径变量提升到try块外,确保finally能访问到:

namespace Test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string tempPath = null;
            try
            {
                tempPath = Path.GetFullPath(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()));
                Directory.CreateDirectory(tempPath);

                // 克隆仓库到tempPath,执行其他逻辑
                // Git.Clone("repo-url", tempPath); // 示例克隆代码
            }
            finally
            {
                if (!string.IsNullOrEmpty(tempPath) && Directory.Exists(tempPath))
                {
                    ProgramExit(tempPath);
                }
            }
        }

        internal static void ProgramExit(string targetPath)
        {
            // 处理仓库中可能存在的只读文件
            foreach (var file in new DirectoryInfo(targetPath).GetFiles("*", SearchOption.AllDirectories))
            {
                file.Attributes = FileAttributes.Normal;
            }
            // 删除目录及所有内容
            Directory.Delete(targetPath, recursive: true);
        }
    }
}

方法二:注册ProcessExit事件(适合多出口场景)

如果你的程序可能从多个地方退出(比如调用Environment.Exit()),可以注册AppDomain.CurrentDomain.ProcessExit事件,确保程序退出时触发清理逻辑:

namespace Test
{
    internal class Program
    {
        private static string _tempPath;

        static void Main(string[] args)
        {
            _tempPath = Path.GetFullPath(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()));
            Directory.CreateDirectory(_tempPath);

            // 注册退出事件
            AppDomain.CurrentDomain.ProcessExit += (sender, e) => ProgramExit();

            // 克隆仓库到_tempPath,执行其他逻辑
            // Git.Clone("repo-url", _tempPath); // 示例克隆代码
        }

        internal static void ProgramExit()
        {
            if (!string.IsNullOrEmpty(_tempPath) && Directory.Exists(_tempPath))
            {
                // 处理只读文件
                foreach (var file in new DirectoryInfo(_tempPath).GetFiles("*", SearchOption.AllDirectories))
                {
                    file.Attributes = FileAttributes.Normal;
                }
                Directory.Delete(_tempPath, recursive: true);
            }
        }
    }
}

关键注意点

  • 只读文件处理:Git仓库里的文件默认可能带有只读属性,直接删除会失败,所以需要先遍历修改文件属性为Normal。
  • 递归删除:使用Directory.Delete(path, recursive: true)确保删除目录下所有子文件和子目录。
  • 空值检查:执行删除前要确认路径存在,避免抛出不存在的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:40:30