VB.Net 3.5 Check if file is in use

后端 未结 5 1692
甜味超标
甜味超标 2021-01-15 03:43

I have an update program that is completely independent of my main application. I run the update.exe to update the app.exe. To check to see if the file is in use, I move it

5条回答
  •  猫巷女王i
    2021-01-15 04:01

    What you could do is replace the target application with a caretaker exe.

    This caretaker then spawns the target application, but also creates a locked file in a shared location. The lock is released and the file is deleted when the app exits.

    Then, before you update the app.exe, you check are there any locked files in the shared location, if there are locked files then the app.exe is in use.

    The caretaker program could be a window-less application, the following console app does pretty much what it needs to do

    class Program
    {
        static string lockFileName;
        static System.IO.StreamWriter lockFileWrtier;
        static void Main(string[] args)
        {
            lockFileName = "AppLock_" + System.IO.Path.GetRandomFileName();
    
            lockFileWrtier = new System.IO.StreamWriter(lockFileName);
    
            System.Diagnostics.Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.EnableRaisingEvents = true;
            p.Exited += new EventHandler(p_Exited);
    
            p.Start();
    
            Console.WriteLine("Press any key to stop");
            Console.ReadKey();
        }
    
        static void p_Exited(object sender, EventArgs e)
        {
            lockFileWrtier.Dispose();
            System.IO.File.Delete(lockFileName);
    
            Console.WriteLine("Process has exited");
        }
    }
    

    The updater then looks for all "AppLock_*" files, and attempts to open them with a write lock, if it can't get a write lock on one of them, the exe is in use.

    Hope this helps.

提交回复
热议问题