c# Cannot delete log file after process stopped
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 => For开发者_高级运维matsToDelete, Directory.GetFiles).SelectMany(fileList => fileList)) {
try {
File.Delete(file);
}catch(IOException io) {
Console.WriteLine("\n" + io.Message);
}
}
}
}
}
Are all of your Services calling Close on the files they're writing to when they are Stop'ped?
Conrad Frix was right, although the service stopped the process was still running and did not release the file.
精彩评论