Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I have a requirement such that if a file in particular path is deleted, then my program should kill an running exe program and sleep for 5 minutes so that my software will automatically start the same exe again. When the file is present in the directory, it should not do anything but simply sleep for 5 minutes. This program should run continuously and it should check for every 5 minutes if the file is present or deleted and based on the result it should take action.

Here my code is working fine but there is a below issue.

Once if someone deletes the file, the file may come back or may not come back for many days. When I executed my code, once I delete the file from the folder it keeps on killing the exe file in every 5 minutes cycle. But it should not do that way instead it should work like, as already file has deleted in this cycle and it killed exe, in the next cycle it should not kill exe even if there is no file. it should kill only if file comes back again and gets deleted.

What I have tried:

C#
<pre>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);
            }
        }
    }
}
Posted
Updated 24-Feb-23 2:50am
Comments
Richard Deeming 24-Feb-23 7:41am    
That sort of behaviour sounds a lot like malware.
PIEBALDconsult 24-Feb-23 8:05am    
Start by writing a flow chart of what you want to have happen.

Add a flag which says "I have killed the external process".
Set it to true when you kill it, and false when the file exists.
Then all you have to do is check it just before you try to kill the EXE.

The advanced version stores and restores the flag in a settings file when the app closes and starts.
 
Share this answer
 
In addition to Griffs advice: another option might be to use the
FileSystemWatcher Class (System.IO) | Microsoft Learn[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900