Trying to create a file and delete it immediately
// (1) create test file and delete it again
File.Create(Path.Combine(folder, "testfile.empt开发者_如何学JAVAy"));
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?
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);
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"));
try ..
File.Create(Path.Combine(folder, "testfile.empty")).Dispose();
File.Delete(Path.Combine(folder, "testfile.empty"));
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");
精彩评论