简体   繁体   English

写入C#中另一个进程(Windows服务)正在使用的文件

[英]Write to a file that is being used by another process (Windows Service) in C#

Is there any way I can write to a file that is being used by another process? 有什么办法可以写入另一个进程正在使用的文件? I have a windows service that creates logs and locks the file until the service is stopped. 我有一个Windows服务,该服务创建日志并锁定文件,直到该服务停止为止。 I have another program that backs up the contents of a textfile and clears the original. 我还有另一个程序可以备份文本文件的内容并清除原始文件。 When I tried my C# program to backup and clear the log that my other service is using it generated an error: "The process cannot access the file because it is being used by another process".. 当我尝试使用C#程序备份并清除其他服务正在使用的日志时,会产生错误:“该进程无法访问该文件,因为该文件正在被另一个进程使用”。

I've been searching and have known that you have to check for a file if it is locked then wait for it until it is not being used by another program. 我一直在搜索,并且知道您必须检查文件是否被锁定,然后等待该文件被另一个程序使用。 I need a code that enables to write to a locked file. 我需要一个能够写入锁定文件的代码。 Is that possible? 那可能吗?

This is my sample windows service code that logs to files every 3 minutes: 这是我的示例Windows服务代码,每3分钟记录一次文件:

private Timer timer = new Timer();
private static FileStream fs = new FileStream(@"D:\Hello.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
private StreamWriter sw = new StreamWriter(fs);

protected override void OnStart(string[] args)
{
    timer.Elapsed += new ElapsedEventHandler(WriteText);
    timer.Interval = 50000; //5 minutes
    timer.Start();
}
public void WriteText(object source, ElapsedEventArgs e)
{
    sw.WriteLine(DateTime.Now);
}
protected override void OnStop()
{
    sw.Close();
    sw.Dispose();
    fs.Close();
    fs.Dispose();   
}

It is required for me to not close the stream unless the service is stopped. 对于我来说,除非服务停止,否则不要关闭流。

Are you tied down to using a StreamWriter? 您是否要使用StreamWriter? You may want to look into using something like log4net for logging. 您可能要考虑使用log4net之类的东西进行日志记录。 You can configure it to roll over logs and you could backup from there, or just simply use that as your backups. 您可以将其配置为滚动日志,然后从那里进行备份,或者只是将其用作备份。

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

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