Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 159677
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T10:54:05+00:00 2026-05-11T10:54:05+00:00

I am running into an issue with a FileSystemWatcher when multiple files are placed

  • 0

I am running into an issue with a FileSystemWatcher when multiple files are placed into the watched directory. I want to parse the file as soon as it is placed in the directory. Typically, the first file parses fine, but adding a second file to the directory causes an access issue. Occasionally, the first file doesn’t even parse. There is only one application running and watching this directory. Eventually, this process will be running on multiple machines and they will be watching a shared directory but only one server can parse each file as the data is imported into a database and there are no primary keys.

Here is the FileSystemWatcher code:

public void Run() {   FileSystemWatcher watcher = new FileSystemWatcher('C:\\temp');   watcher.NotifyFilter = NotifyFilters.FileName;   watcher.Filter = '*.txt';    watcher.Created += new FileSystemEventHandler(OnChanged);    watcher.EnableRaisingEvents = true;   System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); } 

Then the method that parses the file:

private void OnChanged(object source, FileSystemEventArgs e) {   string line = null;    try {     using (FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.None)) {       using (StreamReader sr = new StreamReader(fs)) {         while (sr.EndOfStream == false) {           line = sr.ReadLine();           //parse the line and insert into the database         }       }     }   }   catch (IOException ioe) {     Console.WriteLine('OnChanged: Caught Exception reading file [{0}]', ioe.ToString());   } 

When moving the second file, it is catching

System.IO.IOException: The process cannot access the file ‘C:\Temp\TestFile.txt’ because it is being used by another process.

I would expect to see this error if it was running on multiple machines, but it is only running on one server for now. There shouldn’t be another process using this file – I have them created and copy them into the directory when the application is running.

Is this the proper way to set up the FileSystemWatcher? How can I see what has the lock on this file? Why doesn’t it parse both files – do I have to close the FileStream? I want to keep the FileShare.None option because I only want one server to parse the file – the server that gets to the file first parses it.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T10:54:05+00:00Added an answer on May 11, 2026 at 10:54 am

    A typical problem of this approach is that the file is still being copied while the event is triggered. Obviously, you will get an exception because the file is locked during copying. An exception is especially likely on large files.

    As a workaround you could first copy the file and then rename it and listen to the renaming event.

    Or another option would be to have a while loop checking whether the file can be opened with write access. If it can you will know that copying has been completed. C# code could look like this (in a production system you might want to have a maximum number of retries or timeout instead of a while(true)):

    /// <summary> /// Waits until a file can be opened with write permission /// </summary> public static void WaitReady(string fileName) {     while (true)     {         try         {             using (Stream stream = System.IO.File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))             {                 if (stream != null)                 {                     System.Diagnostics.Trace.WriteLine(string.Format('Output file {0} ready.', fileName));                     break;                 }             }         }         catch (FileNotFoundException ex)         {             System.Diagnostics.Trace.WriteLine(string.Format('Output file {0} not yet ready ({1})', fileName, ex.Message));         }         catch (IOException ex)         {             System.Diagnostics.Trace.WriteLine(string.Format('Output file {0} not yet ready ({1})', fileName, ex.Message));         }         catch (UnauthorizedAccessException ex)         {             System.Diagnostics.Trace.WriteLine(string.Format('Output file {0} not yet ready ({1})', fileName, ex.Message));         }         Thread.Sleep(500);     } } 

    Yet another approach would be to place a small trigger file in the folder after copying is completed. Your FileSystemWatcher would listen to the trigger file only.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 77k
  • Answers 77k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • added an answer You need the account your Oracle service is started under… May 11, 2026 at 3:29 pm
  • added an answer Struts is an entire framework and isn't really going to… May 11, 2026 at 3:29 pm
  • added an answer Is this what you are trying to accomplish? Or do… May 11, 2026 at 3:29 pm

Related Questions

Is there a documented max to the length of the string data you can
I'm running into an issue with a web application that is exhausting all available
I am running into quite an annoying issue while trying to deserialise a specific
I am trying to take a person and display their current insurance along with

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.