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)?
DeleteFileW
now tries to use POSIX semantics if the filesystem supports it. NTFS does. After setting the delete disposition with POSIX semantics, the file is unlinked as soon asDeleteFileW
closes its handle. Existing opens, which must have shared delete access, can continue to access the file, but they cannot unset the delete disposition, unlike the classic Windows delete semantics.SetFileInformationByHandle
:FileDispositionInfo
.1909
, build18363.657
, but a user just commented at stackoverflow.com/a/53561052/45375 that they still see asynchronous behavior as of18363.1316
.