Kasper Hansen
Kasper Hansen

Reputation: 6557

File.Create seems to lock the file. How can I avoid this?

I have 2 threads that communicate by sending files to each other. When Thread #1 does a

// Thread #1
File.Create(@"C:\somedir\response.done");

Then Thread #2 is supposed to delete it.

// Thread #2
while (!File.Exists(@"C:\somedir\response.done"))
    Thread.Sleep(100);


while (File.Exists(@"C:\somedir\response.done"))
    {
        try {
               File.Delete(@"C:\somedir\response.done");
            }
        catch { Thread.Sleep(1000); };

    }

However, the file seems to be locked. There is generated a response.done file in the directory, but it is never deleted. When I try to manually remove it, then

"The action cannot be completed because the file is open in MyProgram. Close the file and try again."

How can I avoid this?

Upvotes: 2

Views: 2712

Answers (4)

Alex
Alex

Reputation: 38529

You can also use .Close()

So your code would become

// Thread #1
File.Create(@"C:\somedir\response.done").Close();

Upvotes: 1

Yahia
Yahia

Reputation: 70379

change your code to

// Thread #1
using (FileStream FS = File.Create(@"C:\somedir\response.done") ) {};

Upvotes: 0

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56202

You need to close FileStream created by File.Create(@"C:\somedir\response.done");.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064004

File.Create returns a FileStream. So... close it:

using(File.Create(path)) {
    // add contents here if needed
}

The using ensures it is Dispose()d, hence closed. Note: it is also possible that some AV systems will interfere with file access, but that is usually not a huge problem.

Upvotes: 11

Related Questions