We have been using the following code for several years.
/// <summary>
/// Opens a file and returns an exclusive handle. The file is deleted as soon as the handle is released.
/// </summary>
/// <param name="path">The name of the file to create</param>
/// <returns>A FileStream backed by an exclusive handle</returns>
/// <remarks>If another process attempts to open this file, they will recieve an UnauthorizedAccessException</remarks>
public static System.IO.FileStream OpenAsLock(string path)
{
var stream = TranslateIOExceptions(() => System.IO.File.Open(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.Delete));
System.IO.File.Delete(path);
return stream;
}
From memory, this code used to leave a file in place until the FileStream was closed. The technique was used as part of a cooperative concurrency lock.
I found a number of other questions which make me think the behavior used to be as the comment describes: the file stays in place until the returned filestream is closed.
Will we ever be able to delete an open file in Windows?
Can using FileShare.Delete cause a UnauthorizedAccessException?
However, as part of an investigation, I've discovered Windows does not behave this way. Instead, the file is deleted as soon as the call to File.Delete is made. I also tried to reproduce the error Hans suggested would occur in the above link without success.
class Program
{
static void Main(string[] args)
{
File.Open("test", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Delete);
File.Delete("test");
File.WriteAllText("test", "hello world");
Console.Write(File.ReadAllText("test"));
Console.ReadLine();
}
}
Unfortunately, the unit test we had which might have caught this change in behavior was not configured correctly to run nightly in our environment, so I can't be certain if it ever ran green.
Was this a real change in behavior? Do we know when it happened? Was it intentional (documented)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…