0

I have similar issue. But I am using a windows service to read file from a specific directory. It is possible multiple files come at same time or one by one. problem is when I put a file it reads but when I put another file it throws file access exception. Please Help. Thanks.

Here is the code:

private static void OnCreated(object source, FileSystemEventArgs e)
    {
        try
        {
            var data = new FileData();
            data.ReadFile(e.FullPath);

        }
        catch (Exception ex)
        {
            WriteLogForError(ex.Message, String.Empty, ErrorLogPath);
        }
    }
Community
  • 1
  • 1
Renascent
  • 184
  • 1
  • 3
  • 17
  • Show you're code.. also, just cos a file is created, doesnt mean its not still being written to.. depends on the size of the file. – BugFinder Aug 08 '16 at 09:03
  • 1
    You don't control the filesystem or other processes (such as the source of the file, as bugfinder says, or anti-virus, etc). Pretty well your only option is to *cope* with the file being unavailable for reading and to sleep/loop until such time as you are able to open the file in the mode you want and it's got the complete contents you're hoping for. – Damien_The_Unbeliever Aug 08 '16 at 09:18
  • @Damien_The_Unbeliever Can you give me an example code for that ? – Renascent Aug 08 '16 at 09:21
  • The duplicate explains the issue exactly and shows workarounds as well. – CodeCaster Aug 08 '16 at 09:33

1 Answers1

0

You try to access the file the moment it is being created. The other process creating the file may still be writing to it, and hence you must not touch it yet.

The solution is awkward: put the filename into some list/queue, start a timer, and after a few seconds try to read it (don't forget a try...catch here and retry on failure, there is no direct notification that the other process has finished its work).

Bernhard Hiller
  • 2,163
  • 2
  • 18
  • 33
  • I m trying Thread.Sleep(); to wait while the file is being written.If I get success I will post answer with code. – Renascent Aug 08 '16 at 09:35