两个程序同时对一个文件分别进行读和写操作,能行吗?
我现在需要写一个这样功能的程序(程序A):从另一个程序(程序B)生成的log文件中读出文件内容。程序B是一直运行的,log文件的内容也是不断增加的,我写的程序A也要一直监视log文件,只要内容一变化,马上就要从文件中读取内容。
我现在担心的是出现log文件只能被一个程序使用,另一个程序打开文件时会失败,被提示文件被占用;
还有个问题就是(在文件能同时被两个程序打开的前提下)我的程序A怎么知道log文件的内容变化了,是否需要先关闭文件再打开啊?还是直接读取文件就能读出更新后的内容?
注意是两个不同的程序,不是两个线程。
急需解决,请高手指教
[最优解释]
建议使用内存共享文件或者管道同步两个进程的数据。
[其他解释]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
// 上次读取行的索引
static Int32 iLastIndex;
static void Display(String path)
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs))
{
Int32 curIndex = 0;
String strText = sr.ReadLine();
// 路过已经读取的行
while (strText != null && iLastIndex != 0 && curIndex++ < iLastIndex)
{
strText = sr.ReadLine();
}
// 显示新增行
while (strText != null)
{
iLastIndex++;
Console.WriteLine(strText);
strText = sr.ReadLine();
}
}
}
}
static void WriteLog(Object path)
{
using (FileStream fs = new FileStream(path.ToString(), FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
while (true)
{
sw.WriteLine(System.DateTime.Now.ToString());
sw.Flush();
Thread.Sleep(1000);
}
}
}
}
static void Main(string[] args)
{
String strLog = "c:\\1.log";
ThreadPool.QueueUserWorkItem(new WaitCallback(WriteLog), strLog);
Thread.Sleep(1000);
iLastIndex = 0;
FileWatcher fileWatcher = new FileWatcher(strLog);
fileWatcher.OnFileChange += Display;
fileWatcher.Start();
Console.ReadKey();
}
}
/// <summary>
/// 监控文件类
/// </summary>
class FileWatcher
{
/// <summary>
/// 文件有改变委托
/// </summary>
/// <param name="path"></param>
/// <param name="lineCount"></param>
public delegate void FileChangeHandler(String path);
/// <summary>
/// 文件有改变时触发事件
/// </summary>
public event FileChangeHandler OnFileChange;
/// <summary>
/// 文件路径
/// </summary>
private String _FilePath;
/// <summary>
/// 文件大小
/// </summary>
private Int64 _FileSize;
private Int64 _FileLastWriteTime;
/// <summary>
/// 监控文件类
/// </summary>
/// <param name="path"></param>
public FileWatcher(String path)
{
_FilePath = path;
}
/// <summary>
/// 启动
/// </summary>
public void Start()
{
if (File.Exists(_FilePath))
{
FileInfo fileInfo = new FileInfo(_FilePath);
_FileLastWriteTime = 0;
_FileSize = 0;
ThreadPool.QueueUserWorkItem(new WaitCallback(FileWatchThread), null);
}
}
/// <summary>
/// 文件监控线程
/// </summary>
/// <param name="obj"></param>
private void FileWatchThread(Object obj)
{
while (true)
{
FileInfo fileInfo = new FileInfo(_FilePath);
Int64 lastWrite = fileInfo.LastWriteTime.Ticks;
Int64 size = fileInfo.Length;
if (size != 0 && (lastWrite != _FileLastWriteTime
[其他解释]