开发者

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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜