简体   繁体   English

如何在运行应用程序时不需要关闭文件时写日志文件?

[英]How to write log file when no need to close file in running application?

We have static class Logger in C#, where log file initializes at starting of application. 我们在C#中有静态类Logger ,其中日志文件在应用程序启动时初始化。 Log files gets roll back (new log file gets created) after each 512 bytes . 512字节后,日志文件将回滚(创建新日志文件)。 Now problem is, I am not able to open current log file externally, because it is being already open in my application. 现在问题是,我无法在外部打开当前日志文件,因为它已在我的应用程序中打开。

I am not able to understand how to deal with this problem. 我无法理解如何处理这个问题。 How to open currently open log file, at same time it should not harm current operations on file. 如何打开当前打开的日志文件,同时不应该损害当前的文件操作。

Thanks. 谢谢。

Using FileShare.ReadWrite is crucial in your case. 在您的情况下,使用FileShare.ReadWrite至关重要。 This should so the trick for you: 这应该是你的诀窍:

using (FileStream stream = File.Open("filePath", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        while (!reader.EndOfStream)
        {
            // do your stuff here
        }
    }
}

To give you an accurate answer, I need to see the code for your logger. 为了给您准确的答案,我需要查看记录器的代码。 But I will explain the idea. 但我会解释这个想法。 Let's say the logger is using System.IO.File.Open() method to create/open the log file for writing. 假设记录器使用System.IO.File.Open()方法创建/打开日志文件进行写入。 Use the overload of the Open() method that allows you to specify the FileShare parameter ( here is the link ) and specify FileShare.Read for that parameter. 使用Open()方法的重载,该方法允许您指定FileShare参数( 此处为链接 )并为该参数指定FileShare.Read This will allow the applications to open the log file in read-only mode, so it will not harm the logging operation. 这将允许应用程序以只读模式打开日志文件,因此不会损害日志记录操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM