【发布时间】:2010-07-20 05:29:44
【问题描述】:
我在服务器上有许多进程,我试图停止、删除日志文件并最终重新启动。我的问题是,一旦所有进程停止(甚至是写入日志文件的进程),我就无法以编程方式删除日志文件(但我可以手动删除)。我收到的错误是“该进程无法访问该文件,因为它正被另一个进程使用。即使我确认该进程已停止并使线程进入睡眠状态,我也无法删除该文件。
我试过 Controller.close() controller.reset();似乎没有任何效果。
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);
}
}
}
}
}
【问题讨论】:
-
您确定
Controller.Stop()没有引发异常吗?即使失败了,您也正在调用DeleteLogFiles()。 -
当我 RDP 到机器并刷新进程列表时,我可以验证进程是否正确停止。