Does DirectoryInfo.GetFiles () return the files that are currently being written to / open?

I browse directories recursively, and I just need to make sure that if the file is open or being written at the moment, it will not be returned in the file list.

(This is for the FTP component, I do not want to send the file if it is already open for writing already)

Thanks Kevin

+3
source share
4 answers

Yes, it will return files that are still in use. They are still in the directory, even if you cannot open them.

Verification code to confirm:

using System;
using System.IO;
using System.Linq;

class Test
{
    static void Main()
    {
        File.Delete("test.tmp");
        // Prints false - the delete worked
        Console.WriteLine(Directory.GetFiles(".")
                                   .Any(x => x.EndsWith("\\test.tmp")));
        using (Stream stream = File.Create("test.tmp"))
        {
            // Prints true, even though the stream is still open
            Console.WriteLine(Directory.GetFiles(".")
                                       .Any(x => x.EndsWith("\\test.tmp")));
        }       
    }
}

, , , . - , -, - , .

+4

. , , .

+1

LastAccessTime ?

0

, , ( ), , .

If the opening does not work, you can safely send them (no one will write or open it). If this fails, you know that you cannot open the file and skip it.

Even if you could check the call to GetFiles (), you may not know that the status is still the same as the first check.

0
source

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


All Articles