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?
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.
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.
To delete a file in C#, you can use System. IO. File. Delete(path) function.
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.
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();
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")){...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With