c# - write - .NET File.Create,can't delete file afterwards




file.create c# (4)

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")){...}

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?


See System.IO.File.Create(String) Method paramter and return value description

Parameters

path Type: System.String The path and name of the file to create.

Return Value

Type: System.IO.FileStream

A FileStream that provides read/write access to the file specified in path.

The FileStream return value is there for IO access to the created file. If you are not interested in writing (or reading) the newly created file, close the stream. That is what the using block is ensuring.


You should use nikmd23's answer in almost all cases. If you can't, because you need to pass the FileStream somewhere else, make sure to call the FileStream.Close method eventually. Preferably you would have the class that 'owns' the FileStream implement IDisposable itself, and close the stream in its Dispose method.

For more information on implementing IDisposable, refer to the MSDN documentation. Easier reading, and more up to date, is Joe Duffy's post on the subject.


nikmd23 has the short answer, the long answer is: the FileStream that File.Create(...) is returning is not being deterministically disposed of, therefore it's file handle is not closed when you're trying to delete it.

As nikmd23 put it, wrapping your File.Create(...) call will with a using statement will make sure the stream is closed and disposed of:

using (FileStream fs = File.Create(path)) { 
  // do anything with the stream if need-be...
}
File.Delete(path); //after it's been disposed of.

The using(...) block is really just compiler-sugar for:

FileStream fs = File.Create(path);
try { 
   // do anything with the stream if need-be...
}
finally { 
  fs.Dispose();
}
File.Delete(path)




file-io