我有两个 C# 应用程序,一个是逐行读取文件(文件 A)并将其内容写入另一个文件(文件 B)。
第二个应用程序使用 FileSystemWatcher 来查看文件 B 的更新时间,并报告程序启动时间和文件更改时间之间的行号差异。
这就是我现在要做的所有事情,最终我想读取文件上次读取时间和当前读取时间之间的行,但直到我可以获得暂停的行差异。
我为应用程序 1 提供的代码是;
static void Main(string[] args)
{
String line;
StreamReader sr = new StreamReader("f:\\watch\\input.txt");
FileStream fs = new FileStream("f:\\watch\\Chat.log", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
while ((line = sr.ReadLine()) != null)
{
sw.WriteLine(line);
Thread.Sleep(200);
Console.WriteLine(line);
sw.Flush();
}
sw.Close();
sr.Close();
}
我为应用程序 2 提供的代码是;
public static int lines = 0;
public static void Main()
{
Run();
}
public static void Run()
{
string[] args = System.Environment.GetCommandLineArgs();
if (args.Length != 2)
{
Console.WriteLine("Usage: Watcher.exe (directory)");
return;
}
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = args[1];
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "Chat.log";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
lines = File.ReadAllLines(args[1] + "\\Chat.log").Length;
Console.WriteLine("File lines: " + lines);
while(Console.Read()!='q');
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
Linework(e.FullPath);
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
public static string Linework(string path)
{
string newstring = " ";
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
int newlines = File.ReadAllLines(path).Length;
Console.WriteLine("Lines now: " + newlines);
}
return newstring;
}
现在,当我尝试同时运行这两个应用程序时,我收到一个异常消息“未处理的异常:System.IO.IOException:该进程无法访问该文件,因为它正在被另一个进程使用”。
我为 ReadWrite 访问设置了两个文件流,为 FileAccess.Write 设置了一个文件流,为 FileAccess.Read 设置了另一个。
关于为什么我会得到这个例外的任何线索?
谢谢休。