我不断轮询文件以查看它是否已更新,即浏览器是否在文件中设置了某个cookie。如果我没有运行应用程序,浏览器会将cookie的值设置为它,但如果我正在运行应用程序,则无法写入我的文件。有没有办法读取文件,以便它也可以同时写入?以下是我正在使用的代码: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Create a timer that polls once every 5 seconds
var timer = new System.Threading.Timer(TimerProc, null, 5000, 5000);
Console.WriteLine("Polling every 5 seconds.");
Console.WriteLine("Press Enter when done:");
Console.ReadLine();
timer.Dispose();
}
static int TickCount = 0;
static void TimerProc(object state)
{
++TickCount;
Boolean found = false;
Console.WriteLine("tick {0}", TickCount);
string curFile = @"C:\Users\ACP\AppData\Local\ETH Zuerich\xul_seb\Profiles\cookies.sqlite-wal";
string line;
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
//Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
StreamReader file = new StreamReader(curFile);
while ((line = file.ReadLine()) != null)
{
if (line.Contains("SEB"))
{
found=true;
}
}
if (found)
{
Console.WriteLine("String exists in the file.");
}
else
{
Console.WriteLine("String does not exist in the file.");
}
file.Close();
}
}
}
答案 0 :(得分:0)
在读取模式下创建FileStream
而不锁定它:
var file = new FileStream(curFile, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);