User1979
User1979

Reputation: 857

File is used by another process: How to solve this Error?

I am trying to open a file, but I received:

The process cannot access the file because it is being used by another process. The File is an XML-Document. Can anyone help?

  string activeDirectory = @"X:\SubGraph\";
  string[] files = Directory.GetFiles(activeDirectory);
  foreach (string fileName in files){
  FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);

Upvotes: 3

Views: 7895

Answers (3)

Ionică Bizău
Ionică Bizău

Reputation: 113345

After using a file, you must to close it, I think:

foreach (string fileName in files)
{
    FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    //your code 
    file.Close();
}

Upvotes: 3

Oscar Foley
Oscar Foley

Reputation: 7025

Under some circumstances Windows locks the files. In your case can be:

  1. Another process is locking the file. It might be windows or you av software or who knows. In order to discover who is locking the file you might several tools like wholockme or Unlocker. These tools will tell you which process is locking the file and even allow you to unlock it.
  2. Maybe you are locking your own file. In your code snippet seems you are not closing the file you are reading (Maybe you can edit your question and add all code). You should remember to include:

    file.Close();

    ... or file will remain open.

Upvotes: 0

Illia Ratkevych
Illia Ratkevych

Reputation: 3711

If you are using this piece of code in some kind of loop you need to close your FileStream each time before finishing loop cycle.

file.Close();

Or use "using" construction like this:

using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
    // your code goes here
    file.Close();
}

Moreover, you better to accustom yourself to close all manually created streams after they are unnecessary anymore.

Upvotes: 0

Related Questions