Let us say that i am writing data to a file handle:
hFile = CreateFile(filename, GENERICREAD | GENERICWRITE, 0, null, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
//[snip error check]
try
{
if (!WriteFile(hFile, buffer, count, ref bytesWritten, null))
throw new Win32Exception(GetLastError());
}
finally
{
CloseHandle();
}
If my write of data failed, i want the file to be deleted when i close the handle. I.e.: i want the file to be "un-CreatFile'd".
i've tried the obvious, delete the file if there was a problem:
hFile = CreateFile(filename, GENERICREAD | GENERICWRITE, 0, null, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
//[snip error check]
try
{
try
{
if (!WriteFile(hFile, buffer, count, ref bytesWritten, null))
throw new Win32Exception(GetLastError());
}
finally
{
CloseHandle();
}
}
catch
{
DeleteFile(filename);
throw;
}
There are two problems with that approach:
- There's a race condition, where someone could open my file after i close it, but before i delete it
- i might have permission to Create a file, but not the Delete it.
What i would like is a way to retroactively specify:
FILE_FLAG_DELETE_ON_CLOSE
: The file is to be deleted immediately after all of its handles are closed, which includes the specified handle and any other open or duplicated handles.
to the file that i have open.
i created the file! Surely i can uncreate it! All because i forgot to specify a flag before-hand?