Reading the file immediately after writing it, I get all zeros (.net)

I have a program that should download files from a directory as soon as they are written. I received a FileSystemWatcher to notify me of directory changes. Instead of checking the event for what has changed, I just listed the files and started processing everything that I found.

In order not to try to read the file that is still being written, I have the code:

try {
    fs = fi.Open(FileMode.Open, FileAccess.ReadWrite,
                    FileShare.None);
    message = new byte[fs.Length];
    int br = fs.Read(message, 0, (int)fi.Length);
}
catch (Exception e) {
    // I'll get it next time around
    return;
}
finally {
    if (fs != null)
        fs.Close();
}

The problem is that for some files, about 1 in 200, the program reads all zeros. The file length is correct, but the content seems to be zero. When I check the last file, I find that it contains the actual correct data. I thought a way to open a file would prevent premature access to the file.

, DOS " InFile_0 * dropdir" ( 100 ). , : 1) 2) .

, , ?

: - . , .

+3
2

. ( ..), .

, , , "whatever.tmp", , . .tmp.

"sentinel" . , , . , / >= / .

, , / /. ( , , , ), .

. .

+2

, @Ollie Jones.

, .

, . " ", :

fi.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

, . , , - . , .

+1

Source: https://habr.com/ru/post/1786545/


All Articles