Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to a filestream when the file is deleted by a different process?

In C#, I open a file with FileShare.Delete. This allows me to open the file without restricting other processes from deleting it. For example:

using (FileStream fs = new FileStream(@"C:\temp\1.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
    int len = (int)fs.Length;
    byte[] array = new byte[len];
    int bytesRead = fs.Read(array, 0, len);
}

My questions are:

  1. What happens if the file is deleted by a different process after we created the stream, but before we read it? Does the operating system keep a copy of the file until the stream\handle is closed?
  2. Can I rely on reading the deleted file without getting any errors, or the wrong content?
like image 663
MoonRabbit Avatar asked Oct 10 '16 08:10

MoonRabbit


1 Answers

The file is marked for deletion, but is not actually deleted until the last open handle to it is closed, as described in the documentation for DeleteFile.

Note that you cannot open a new handle to a file that is marked for deletion, but the file will still appear in directory listings and cannot be replaced by a file of the same name until it has actually been deleted. This is unlike Unix systems in which the file disappears from the directory (is "unlinked") immediately. As Ben suggests in the comments, you can work around this by renaming and/or moving the file before deleting it.

Also, as MoonRabbit pointed out, you can "delete" an open file using Explorer, but that is because that only moves the file to the recycle bin. The Shift+Delete option to delete a file immediately won't work.

like image 90
Harry Johnston Avatar answered Sep 22 '22 10:09

Harry Johnston