marak
marak

Reputation: 270

File used by another process exception

I have two C# .NET applications:

App2 continuously monitors for the changes in XML file, for which I am using FileSystemWatcher.

As soon as the App1 completes writing to the file, App2 reads the changes.

I made sure my App2 is reading the XML only with Read access, but still sometimes my App1 throws an exception:

"The process cannot access the file 'C:\xmlFile' because it is being used by another process". Here is my code snippet in App2 which is reading the file.

Here is my code:

using (var stream = File.Open(filePath,FileMode.Open,FileAccess.Read))
{
    using (XmlReader reader = XmlReader.Create(stream))
    {
        while (reader.Read())
        {
            // Only detect start elements.
            if (reader.IsStartElement())
            {
                switch (reader.Name)
                {
                    case "Component":
                        fileElements.ComponentName = reader["Name"];
                        fileElements.DateRun = reader["DateRun"];
                        fileElements.Passed = reader["Passed"];
                        break;
                }
            }
        }

        if (filePath.ToLower().Contains("ebsserver"))
        {
            UpdateDataTable1(fileElements);
        }
        else if (filePath.ToLower().Contains("ebsui"))
        {
            UpdateDataTable2(fileElements);
        }
        else
        {
            UpdateDataTable3(fileElements);
        }
    }
}

How can I fix this?

Upvotes: 3

Views: 1012

Answers (2)

Aydin
Aydin

Reputation: 15294

You were missing the FileShare parameter on the File.Open method

    using (var stream = File.Open(filePath,FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (XmlReader reader = XmlReader.Create(stream))
    {
        while (reader.Read())
        {
            // Only detect start elements.
            if (!reader.IsStartElement())
            {
                continue;
            }

            if (reader.Name != "Component")
            {
                continue;
            }

            fileElements.ComponentName  = reader["Name"];
            fileElements.DateRun        = reader["DateRun"];
            fileElements.Passed         = reader["Passed"];
       }

       if (filePath.ToLower().Contains("ebsserver"))
       {
           UpdateDataTable1(fileElements);
       }
       else if (filePath.ToLower().Contains("ebsui"))
       {
           UpdateDataTable2(fileElements);
       }
       else
       {
           UpdateDataTable3(fileElements);
       }
   }

Upvotes: 0

bytecode77
bytecode77

Reputation: 14840

You have to use FileShare.ReadWrite in the reading app to signalize that there will be no lock when opening. It's the same mechanism that is used in, for instance, text editors which open files which are also written to.

File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

Upvotes: 1

Related Questions