Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET File.Create , can't delete file afterwards

Tags:

c#

.net

file-io

Using method: System.IO.File.Create()

After the file gets created, it still remains used by a process, and I can't delete it.

Any idea how I can better create the file, should be a 0byte file, and then somehow close and dispose?

like image 335
JL. Avatar asked Sep 25 '09 14:09

JL.


People also ask

Why won't my files let me delete a file?

It's most likely because another program is currently trying to use the file. This can occur even if you don't see any programs running. When a file is open by another app or process, Windows 11/10 puts the file into a locked state, and you can't delete, modify, or move it to another location.

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

Use Shift + Delete to Force Delete File/Folder. You can select the target file or folder and press Shift + Delete keyboard shortcut to delete the file/folder permanently. This file deletion method won't pass the Recycle Bin.

How do you force delete a file in C#?

To delete a file in C#, you can use System. IO. File. Delete(path) function.

How do I delete an existing file and create a new file in C#?

C# Delete FileDelete(path) method is used to delete a file in C#. The File. Delete() method takes the full path (absolute path including the file name) of the file to be deleted. If file does not exist, no exception is thrown.


2 Answers

The Create method not only creates the file, it opens it and return a FileStream object that you can use to write to the file.

You have to close the file after yourself, otherwise it will not be closed before the garbage collector cleans up the FileStream object.

The easiest way is to simply close the file using the reference that the Create method returns:

File.Create(fileName).Close();
like image 70
Guffa Avatar answered Oct 29 '22 21:10

Guffa


JL,

You should wrap your call to .Create in a using statement so that the FileStream that .Create returns will be closed properly. IE:

using (File.Create("path")){...}
like image 21
nikmd23 Avatar answered Oct 29 '22 23:10

nikmd23