Reputation: 857
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
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
Reputation: 7025
Under some circumstances Windows locks the files. In your case can be:
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
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