Est-il possible d'ouvrir un fichier dans .NET avec un accès en écriture non exclusif? Si c'est le cas, comment? Mon espoir est d'avoir deux processus ou plus écrire dans le même fichier en même temps.Comment ouvrir un fichier pour un accès en écriture non-exclusif en utilisant .NET
Editer: Voici le contexte de cette question: J'écris un simple HTTPModule de journalisation pour IIS. Étant donné que les applications exécutées dans différents pools d'applications s'exécutent en tant que processus distincts, j'ai besoin d'un moyen de partager le fichier journal entre les processus. Je pourrais écrire une routine de verrouillage de fichier complexe, ou un écrivain paresseux, mais c'est un projet de jeter, donc ce n'est pas important.
C'est le code de test que j'ai utilisé pour comprendre le processus.
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;
}
}
}
Je suppose que vous voulez dire que d'autres puissent le lire pendant que vous écrivez - il semble étrange de vouloir permettre à plusieurs auteurs. –