Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to create a file and delete it immediately

Tags:

c#

file

// (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?

like image 784
Kasper Hansen Avatar asked Mar 15 '11 14:03

Kasper Hansen


People also ask

How do you make a file automatically delete itself?

Setting a file to auto-delete button for the file and select More Actions>Set Expiration. Check off the box to Auto-delete this item on a selected date and use the box to select the appropriate date for deletion. Click Save to save your changes.

Why wont a file let me delete it?

In most cases, the reason you cannot delete a file is quite simple. The file or a file from the folder is still open or being used by another program.

How do I force a file to delete?

Press Shift + Delete to force delete a file or folder If the problem is due to the Recycle Bin, you can select the target file for folder, and press Shift + Delete keyboard shortcut to permanently delete it.

How do you force delete a file that won't delete?

One is simply using the delete option, and the other one is deleting files permanently. When you can't delete a file normally, you can delete undeletable files Windows 10 by selecting the target file or folder and then press Shift + Delete keys on the keyboard for a try.


4 Answers

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);
like image 190
Marc Gravell Avatar answered Nov 03 '22 02:11

Marc Gravell


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"));
like image 20
Oded Avatar answered Nov 03 '22 01:11

Oded


try ..

File.Create(Path.Combine(folder, "testfile.empty")).Dispose();
File.Delete(Path.Combine(folder, "testfile.empty"));
like image 39
bleeeah Avatar answered Nov 03 '22 01:11

bleeeah


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");
like image 22
Polaris Avatar answered Nov 03 '22 00:11

Polaris