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

如何用C#控制台程序实现文件删除时终止进程且避免重复操作

文件状态触发进程终止的逻辑优化

需求说明

  • 当指定路径的文件被删除时,终止运行中的指定exe,之后休眠5分钟(供其他软件重启该exe)
  • 当文件存在时,仅休眠5分钟
  • 程序持续运行,每5分钟检查一次文件状态并执行对应操作

现有问题

当前代码可正常运行,但存在逻辑缺陷:文件被删除后若长期未恢复,代码会每5分钟重复终止目标exe。预期仅在文件从存在变为删除的瞬间执行终止操作,文件持续缺失时不重复执行。

当前代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                string path = "C:\\Experiment\\folder\\database\\data.tou";
                if (File.Exists(path))
                {
                    Thread.Sleep(60000);
                }
                else
                {
                    Process[] pname = Process.GetProcessesByName("notepad");
                    if (pname.Length > 0)
                    {
                        pname[0].Kill();
                    }
                    else
                    {
                        
                    }
                }
                Thread.Sleep(60000);
            }
        }
    }
}

修复方案

核心是通过记录文件的上一次状态,仅在状态发生变化(存在→不存在)时执行终止操作,同时修正休眠时间为需求要求的5分钟:

using System;
using System.IO;
using System.Threading;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = "C:\\Experiment\\folder\\database\\data.tou";
            // 初始化记录文件初始状态
            bool previousFileExists = File.Exists(path);
            // 5分钟对应的毫秒数
            int sleepDuration = 5 * 60 * 1000;

            while (true)
            {
                bool currentFileExists = File.Exists(path);

                // 仅当文件从存在变为不存在时,执行终止操作
                if (previousFileExists && !currentFileExists)
                {
                    Process[] targetProcesses = Process.GetProcessesByName("notepad");
                    if (targetProcesses.Length > 0)
                    {
                        targetProcesses[0].Kill();
                    }
                }

                // 更新状态记录
                previousFileExists = currentFileExists;
                // 统一休眠5分钟
                Thread.Sleep(sleepDuration);
            }
        }
    }
}

关键优化点

  • 新增previousFileExists变量追踪文件状态变化,避免重复触发终止逻辑
  • 将休眠时间统一设置为5分钟(300000毫秒),匹配需求描述
  • 仅在存在→不存在的状态切换时执行进程终止,符合预期逻辑
  • 移除冗余的嵌套Sleep,简化循环结构

内容的提问来源于stack exchange,提问作者Krishna Chaitanya Bezawada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:57:27