给定一个现有的临时目录(d:\ temp),我们运行以下代码
[Test]
public void Test()
{
for (int i = 0; i < 10000; i++)
{
Console.WriteLine(i);
File.WriteAllText(@"d:\temp\file.txt", " ");
File.Delete(@"d:\temp\file.txt");
}
}
在for循环中一段时间后,我们看到异常:
System.UnauthorizedAccessException : Access to the path 'd:\temp\file.txt' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamWriter.CreateFile(String path, Boolean append)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
at System.IO.File.WriteAllText(String path, String contents, Encoding encoding)
at System.IO.File.WriteAllText(String path, String contents)
当然,如果我们更改添加Thread.Sleep(10)的代码,如:
[Test]
public void Test()
{
for (int i = 0; i < 10000; i++)
{
Console.WriteLine(i);
File.WriteAllText(@"d:\temp\file.txt", " ");
File.Delete(@"d:\temp\file.txt");
Thread.Sleep(10);
}
}
一切都很好,但我们不想添加睡眠以使一切正常。为什么这样的行为呢?