【问题标题】:c# Cannot delete log file after process stoppedc#进程停止后无法删除日志文件
【发布时间】: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 到机器并刷新进程列表时,我可以验证进程是否正确停止。

标签: file-io c#-4.0 process


【解决方案1】:

当它们被停止时,您的所有服务是否都在对正在写入的文件调用 Close?

【讨论】:

  • 它不在我给出的示例中,但我确实尝试过,只是验证了由于某种原因它没有释放文件。奇怪的是它什么时候可以让我手动删除它们。
  • 您是否在调用 public static void Stop() 后手动删除文件 - 一旦进程结束,文件的句柄将被释放。
  • 您可能想尝试使用 ProcessExplorer 并使用 CTRL-F 来验证哪个进程是罪魁祸首。你可以在这里得到它technet.microsoft.com/en-us/sysinternals/bb896653.aspx
【解决方案2】:

Conrad Frix 是对的,尽管服务停止了进程仍在运行并且没有释放文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多