Kasper Hansen
Kasper Hansen

Reputation: 6557

Trying to create a file and delete it immediately

// (1) create test file and delete it again
File.Create(Path.Combine(folder, "testfile.empty"));
File.Delete(Path.Combine(folder, "testfile.empty"));

The last line throws an exception:

The process cannot access the file '\\MYPC\C$_AS\RSC\testfile.empty' because it is being used by another process.

Why is that?

Upvotes: 10

Views: 11513

Answers (4)

Polaris
Polaris

Reputation: 3793

Create method returns a filestream which must be close before making other operations:

FileStream fs=File.Create( "testfile.empty");
fs.Close();
File.Delete("testfile.empty");

Upvotes: 1

bleeeah
bleeeah

Reputation: 3604

try ..

File.Create(Path.Combine(folder, "testfile.empty")).Dispose();
File.Delete(Path.Combine(folder, "testfile.empty"));

Upvotes: 1

Oded
Oded

Reputation: 499372

When you created the file, you are using it until you close it - you have not done so, hence the error.

In order to close the file, you should be wrapping the creation in a using statement:

using(var file = File.Create(Path.Combine(folder, "testfile.empty")))
{
}
File.Delete(Path.Combine(folder, "testfile.empty"));

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1064164

File.Create hands you back a stream, that you haven't closed.

using(var file = File.Create(path)) {
   // do something with it
}
File.Delete(path);

should work; or easier:

File.WriteAllBytes(path, new byte[0]);
File.Delete(path);

or even just:

using(File.Create(path)) {}
File.Delete(path);

Upvotes: 24

Related Questions