问题
In C# 4.0, MemoryMappedFile
has several factory methods: CreateFromFile
, CreateNew
, CreateOrOpen
, or OpenExisting
. I need to open the MemoryMappedFile
if it exists, and if not, create it from a file. My code to open the memory map looks like this:
try
{
map = MemoryMappedFile.OpenExisting(
MapName,
MemoryMappedFileRights.ReadWrite
| MemoryMappedFileRights.Delete);
}
catch (FileNotFoundException)
{
try
{
stream = new FileStream(
FileName,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.Read | FileShare.Delete);
map = MemoryMappedFile.CreateFromFile(
stream, MapName, length + 16,
MemoryMappedFileAccess.ReadWrite,
null,
HandleInheritability.None,
false);
}
catch
{
if (stream != null)
stream.Dispose();
stream = null;
}
}
It pretty much works the way I want it to, but it ends up throwing an exception on OpenExisting
way too often. Is there a way to check whether the MemoryMappedFile
actually exists before I try to do the OpenExisting
call? Or do I have to deal with the exception every single time?
Also, is there a way to find out if the current handle is the last one to have the MemoryMappedFile
open, to determine if the file will be closed when the current handle is disposed?
回答1:
You can use MemoryMappedFile.CreateOrOpen:
map = MemoryMappedFile.CreateOrOpen(
MapName, length + 16,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileOptions.None, null, HandleInheritability.None);
回答2:
See Han Passant's comment under the original question for accepted answer. Since I can't mark it as accepted, I'll just refer to it here and mark this as accepted.
来源:https://stackoverflow.com/questions/9422082/how-to-detect-if-a-memorymappedfile-is-in-use