2

I need to create the temp file while I do some work and to delete the file automatically when the work will be finished. This file contents some info which is for reading by other applications and becomes unnecessary when the work is completed. I try to use FileShare.Read and FileOptions.DeleteOnClose but at this case other applications can't read the file.

var documentName = "some-document";
var editor = "Bob";

using (var fs = new FileStream($"{documentName}.log", FileMode.Create,
    FileAccess.Write, FileShare.Read, 4 * 1024, FileOptions.DeleteOnClose))
{
    string info = $"{DateTime.Now}: The '{documentName}.xml' file " +
        $"is edited by {editor} right now.";
    var data = Encoding.UTF8.GetBytes(info);
    fs.Write(data, 0, data.Length);

    // Here is some big work with some-document.xml file

    #if DEBUG
        fs.Flush();
    #endif
} // <-- I set the breakpoint here in IDE and try to open 
  // the some-document.log file by Notepad++.
  // But Notepad++ can't to do it.

If I comment the , 4 * 1024, FileOptions.DeleteOnClose code chunk then other applications can read my some-document.log file. But at this case I am to write additional code chunk for delete my temp file (I would like to awoid it...).

Why FileShare.Read doesn't work in combination with FileOptions.DeleteOnClose?

Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182
  • 1
    here's answer on similar question https://stackoverflow.com/a/546387/225389 – Chizh Apr 18 '18 at 09:52
  • 1
    To read such file from another process you need to open it like this: `new FileStream($"test.log", FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Write | FileShare.Delete)`. Of course not much applications open with FileShare.Delete (notepad++ doesn't), so you have this problem. – Evk Apr 18 '18 at 10:36

0 Answers0