views:

34

answers:

2

I have many processes on a server which Im attempting to stop, delete the log files, and eventually restart. My problem is that once all the processes stop (even the one that writes to the log file), Im unable to programatically delete the log files (but I can manually). The error I receieve is "the process cannot access the file because it is being used by another process. Even when I verify the process has stopped and put the thread to sleep I cannot delete the file.

Ive tried Controller.close() controller.reset(); nothing seems to work.

        public static void Stop()
        {
            foreach (var service in Services) {
                Controller.ServiceName=service;

                if (Controller.Status == ServiceControllerStatus.Stopped) {
                    Console.WriteLine("{0} was not running.", Controller.DisplayName);

                }else {
                    Console.WriteLine("Stopping {0} on {1}", Controller.DisplayName, Controller.MachineName);

                    try {
                        Controller.Stop();
                        Controller.WaitForStatus(ServiceControllerStatus.Stopped);

                    } catch (InvalidOperationException) {
                        Console.WriteLine("Could not stop {0}", Controller.DisplayName);
                }
                    Console.WriteLine("Service {0} now set to {1}", Controller.DisplayName, Controller.Status);
                }
            }

            Console.WriteLine("\nDeleting Log Files on " + Controller.MachineName + " ...");
            DeleteLogFiles();

        }

        private static void DeleteLogFiles()
        {
            foreach (var file in
                Paths.SelectMany(path => FormatsToDelete, Directory.GetFiles).SelectMany(fileList => fileList)) {
                try {
                    File.Delete(file);
                }catch(IOException io) {
                    Console.WriteLine("\n" + io.Message);
                }
            }
        }
    }
}
A: 

Are all of your Services calling Close on the files they're writing to when they are Stop'ped?

Will A
its not in the example I gave, but I did try it and just verified that for some reason its not releasing the file. the odd part is when it will let me manually delete them.
Farstucker
You might want to try and use ProcessExplorer and use CTRL-F to verify which process is the culprit. You can get it here http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
Conrad Frix
Do you manually delete the files once your public static void Stop() has been called, though - once the process goes away then the handles to the files will be released anyway.
Will A
A: 

Conrad Frix was right, although the service stopped the process was still running and did not release the file.

Farstucker