是否可以使用非独占写访问权限在.NET中打开文件?如果是这样,怎么样?我希望有两个或更多进程同时写入同一个文件。
编辑:以下是此问题的上下文:我正在为IIS编写一个简单的日志记录HTTPModule。由于在不同应用程序池中运行的应用程序作为不同的进程运行,我需要一种在进程之间共享日志文件的方法。我可以编写一个复杂的文件锁定例程,或者一个懒惰的编写器,但这是一个丢弃的项目,所以它并不重要。
这是我用来计算过程的测试代码。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
namespace FileOpenTest
{
class Program
{
private static bool keepGoing = true;
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
Console.Write("Enter name: ");
string name = Console.ReadLine();
//Open the file in a shared write mode
FileStream fs = new FileStream("file.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite);
while (keepGoing)
{
AlmostGuaranteedAppend(name, fs);
Console.WriteLine(name);
Thread.Sleep(1000);
}
fs.Close();
fs.Dispose();
}
private static void AlmostGuaranteedAppend(string stringToWrite, FileStream fs)
{
StreamWriter sw = new StreamWriter(fs);
//Force the file pointer to re-seek the end of the file.
//THIS IS THE KEY TO KEEPING MULTIPLE PROCESSES FROM STOMPING
//EACH OTHER WHEN WRITING TO A SHARED FILE.
fs.Position = fs.Length;
//Note: there is a possible race condition between the above
//and below lines of code. If a context switch happens right
//here and the next process writes to the end of the common
//file, then fs.Position will no longer point to the end of
//the file and the next write will overwrite existing data.
//For writing periodic logs where the chance of collision is
//small, this should work.
sw.WriteLine(stringToWrite);
sw.Flush();
}
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
keepGoing = false;
}
}
}
答案 0 :(得分:7)
使用File.Open打开文件时使用FileShare枚举。具体来说,使用FileShare.ReadWrite。
答案 1 :(得分:6)
FileStream类有一个constructor,它有几个选项,包括FileShare
new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
答案 2 :(得分:0)
我在procbits.com上找到了一个非常有用的答案:
日志文件生成器:(第一个过程)
static void Main(string[] args) {
var file = @"C:\logfile.txt";
var fs = File.Open(file, FileMode.Append, FileAccess.Write, FileShare.Read);
var sw = new StreamWriter(fs);
sw.AutoFlush = true;
sw.WriteLine("some data");
sw.WriteLine("some data2"); //set breakpoint here
sw.Close();
}
日志文件阅读器:(第二个过程)
static void Main(string[] args) {
var file = @"C:\logfile.txt";
var fs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var sr = new StreamReader(fs);
var l1 = sr.ReadLine();
var l2 = sr.ReadLine();
sr.Close();
}
总之,这是可行的,因为FileShare权限设置正确。
答案 3 :(得分:-1)
不可能。了解如何将文件读取/写入光盘。
编辑:由于所有的downvotes,我想我会解释一下。多个进程绝对不可能在同一时间写入同一个文件。当一个进程正在写入时,该文件通常对其他编写者不可用,这意味着其他进程必须等到第一个进程不再写入该文件。