2010-07-16 84 views
0

我在一个服务器上有很多进程,我试图停止,删除日志文件,并最终重新启动。我的问题是,一旦所有进程停止(即使是写入日志文件的进程),我无法以编程方式删除日志文件(但我可以手动)。我接受的错误是“进程无法访问该文件,因为它正在被另一个进程使用,即使当我验证进程已停止并且让线程进入睡眠状态时,我也无法删除该文件。c#在进程停止后无法删除日志文件

Ive tried 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); 
       } 
      } 
     } 
    } 
} 
+0

你确定'Controller.Stop()'没有引发异常吗?即使这个失败,你也调用DeleteLogFiles()。 – ChrisF 2010-07-16 20:01:38

+0

当我将RDP发送到机器并刷新进程列表时,我可以验证进程是否正常停止。 – Ryan 2010-07-16 20:06:58

回答

0

康拉德Frix是正确的? ,虽然服务停止了,但进程仍在运行,并没有释放文件。

0

时对其进行Stop'ped所有服务的号召,他们正在写入的文件关闭

+0

它没有在我给出的例子中,但我确实尝试过,只是验证了由于某种原因它没有释放文件。奇怪的是它会让我手动删除它们。 – Ryan 2010-07-16 20:16:53

+3

您可能想尝试使用ProcessExplorer并使用CTRL-F来验证哪个进程是罪魁祸首。你可以在http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx – 2010-07-16 20:22:00

+0

当你调用public static void Stop()之后手动删除这些文件 - 但是 - 一旦进程消失那么文件的句柄将被释放。 – 2010-07-16 20:22:00