1

I have a slight problem. What my application is supose to do, is to watch a folder for any newly copied file with the extention '.XSD' open the file and assign the lines to an array. After that the data from the array should be inserted into a MySQL database, then move the used file to another folder if it's done.

The problem is that the application works fine with the first file, but as soon as the next file is copied to the folder I get this exception for example: 'The process cannot access the file 'C:\inetpub\admission\file2.XPD' because it is being used by another process'.

If two files on the onther hand is copied at the same time there's no problem at all.

The following code is on the main window:

public partial class Form1 : Form
{
    static string folder = specified path;        
    static FileProcessor processor;

    public Form1()
    {
        InitializeComponent();
        processor = new FileProcessor();
        InitializeWatcher();
    }

    static FileSystemWatcher watcher;

    static void InitializeWatcher()
    {
        watcher = new FileSystemWatcher();
        watcher.Path = folder;

        watcher.Created += new FileSystemEventHandler(watcher_Created);
        watcher.EnableRaisingEvents = true;
        watcher.Filter = "*.XPD";
    }

    static void watcher_Created(object sender, FileSystemEventArgs e)
    {
        processor.QueueInput(e.FullPath);
    }

}

As you can see the file's path is entered into a queue for processing which is on another class called FileProcessor:

class FileProcessor
{
    private Queue<string> workQueue;
    private Thread workerThread;
    private EventWaitHandle waitHandle;

    public FileProcessor()
    {
        workQueue = new Queue<string>();
        waitHandle = new AutoResetEvent(true);
    }

    public void QueueInput(string filepath)
    {
        workQueue.Enqueue(filepath);

        if (workerThread == null)
        {
            workerThread = new Thread(new ThreadStart(Work));
            workerThread.Start();
        }

        else if (workerThread.ThreadState == ThreadState.WaitSleepJoin)
        {
            waitHandle.Set();
        }
    }

    private void Work()
    {
        while (true)
        {
            string filepath = RetrieveFile();

            if (filepath != null)
                ProcessFile(filepath);
            else
                waitHandle.WaitOne();
        }
    }

    private string RetrieveFile()
    {
        if (workQueue.Count > 0)
            return workQueue.Dequeue();
        else
            return null;
    }

    private void ProcessFile(string filepath)
    {
        string xName = Path.GetFileName(filepath);
        string fName = Path.GetFileNameWithoutExtension(filepath);

        string gfolder = specified path;            
        bool fileInUse = true;
        string line;
        string[] itemArray = null;
        int i = 0;


        #region Declare Db variables

        //variables for each field of the database is created here

        #endregion


        #region Populate array

        while (fileInUse == true)
        {
            FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read,           
                                           FileShare.ReadWrite);

            StreamReader reader = new StreamReader(fs);

            itemArray = new string[75];

            while (!reader.EndOfStream == true)
            {
                line = reader.ReadLine();
                itemArray[i] = line;
                i++;
            }
            fs.Flush();
            reader.Close();
            reader.Dispose();
            i = 0;
            fileInUse = false;
        }

        #endregion

        #region Assign Db variables

        //here all the variables get there values from the array

        #endregion

        #region MySql Connection

        //here the connection to mysql is made and the variables are inserted into the db

        #endregion

        #region Test and Move file

        if (System.IO.File.Exists(gfolder + xName))
        {
            System.IO.File.Delete(gfolder + xName);
        }

        Directory.Move(filepath, gfolder + xName);

        #endregion

    }
}

The problem I get occurs in the Populate array region. I read alot of other threads and was lead to believe that by flushing the file stream would help...

I am also thinking of adding a try..catch for if the file process was successful, the file is moved to gfolder and if it failed, moved to bfolder

Any help would be awesome

Tx

3
  • Looks like some sort of race condition. When VS breaks on the Exception, check in the View->Debug->Threads and see if there's another one with a file in use still. EDIT: Also, the FileStream is not Disposed, try putting it in a using {...}
    – DaveShaw
    Jan 6, 2011 at 23:49
  • Not that I have any idea what is the problem, but just to clarify for others: when exactly do you get the exception? When using the reader?
    – user348905
    Jan 6, 2011 at 23:49
  • Not sure of the while (fileInUse == true) statement. Try a using(FileStream fs = FileStream(...)) statement here instead.
    – k rey
    Jan 6, 2011 at 23:56

2 Answers 2

3

You're not disposing of your FileStream instance, so a lock remains on the file. Change your code to use using blocks:

using (var fileStream = new FileStream(...))
{
    using (var reader = new StreamReader(fileStream))
    {

    }
}

These using blocks will ensure the instances are correctly disposed of.

Also, why are you calling Flush on the file stream? You're not writing anything with it...

1
  • 2
    Or more consicely: using (var reader = File.OpenText(path)) { ... }
    – Serguei
    Jan 7, 2011 at 0:03
0

I would suggest : 1° use the using syntax on StreamReader 2° use the using syntax on FileStream

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.