我有两个 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。
关于为什么我会收到此异常的任何线索?
谢谢
槎。