我有兩個C#應用程序,一個是逐行讀取文件(文件A)並將其內容寫入不同的文件(文件B)。爲什麼在嘗試從正在寫入的文件讀取時收到未處理的異常:System.IO.IOException?
第二個應用程序使用FileSystemWatcher for File 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。
任何線索,爲什麼我會得到這個異常?
謝謝 哎。
哪個應用程序出錯? – spinon 2010-07-06 17:59:41
FileShare.ReadWrite負責同時打開文件,但這是否也有助於同時訪問? – apoorv020 2010-07-06 18:06:44
@ apoorv020:是的,即使是其他進程。但可能需要額外的權限。 – 2010-07-06 18:21:23