Wait for the TXT file to be readable by C #

My application uses "FileSystemWatcher ()" to raise an event when a TXT file is created by the "X" application and then reads its contents.

application "X" creates a file (my application detects it successfully), but it takes some time to fill in the data on it, so this txt file cannot be read during creation, so im

looking for something to wait for the txt file to be readable. not a static delay, but something related to this file.

any help? THX

+3
source share
9 answers

You can open and read a locked file like this

using (var stream = new FileStream(@"c:\temp\file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
   using (var file = new StreamReader(stream)) {
      while (!file.EndOfStream) {
         var line = file.ReadLine();
         Console.WriteLine(line);
      }
   }
}

, , .

+1

:

myfile.tmp

, ,

myfile.txt

.txt

+4

, , - , . , - ...

bool FileRead = false;

while (!FileRead)
{
   try
   {

      // code to read file, which you already know
      FileRead = true;
   }
   catch(Exception)
   {
      // do nothing or optionally cause the code to sleep for a second or two

   }


}
+3

Changed , . - , .

+2

X . X .NET- ? FileInfo FileShare ( FileShare.Read).

X, . FileInfo.Open. FileShare.None. , . , X .

+1

pdf-, - :

using (FileSystemWatcher watcher = new FileSystemWatcher(folder))
{
    if(!File.Exists(docname))
        for (int i = 0; i < 3; i++)
            watcher.WaitForChanged(WatcherChangeTypes.Created, i * 1000);
}

, 6 ( , , , , ), , - .

for, , , . , , , .

+1

.

Changed , , , .

, , , , , .

0

, , . .

0

, . .
, , .Flush() .Close() , .

-1

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


All Articles