Reputation: 5761
Working on an app that will use memory-mapped files for some inter-(or is it intra?)application communication, and I want to make sure when I randomly generate a memory-mapped memory-only file, I don't accidentally generate or get a duplicate that already exists (that ultra-rare case when the planets align and something like that might happen). Any ideas on how to prevent that? System.IO.MemoryMappedFiles does not appear to have a File.Exists() method...I guess I could try OpenOrCreate() and deal with any access violations, etc., but this would be getting nasty quick.
Upvotes: 0
Views: 716
Reputation: 93434
First, you can prevent a naming conflict by using a unique name for your file, such as your company name, or your application name, or both. No other app is going to have those in the file name. If you're worried about two copies of the same app, then you can simply open the file in Create only mode, rather than Create or Open.
Upvotes: 0
Reputation: 26
From: Programming Memory-Mapped Files with the .NET Framework - CodeProject.com
static void Main(string[] args)
{
string name = "NetMMFSingle";
// Create named MMF
try
{
var mmf = MemoryMappedFile.CreateNew(name, 1);
} catch
{
Console.WriteLine("Instance already running...");
return;
}
ConsoleKeyInfo key = Console.ReadKey();
// Your real code follows...
}
Upvotes: 1
Reputation: 273229
Using File.Exists()
wouldn't be concurrency-safe anyway.
The best thing to do: base a Filename on a Guid.
Upvotes: 2