1

Given an existing temp directory (d:\temp), we run the following code

[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");
        }
    }

After a while in the for loop, we see the exception:

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)

of course if we change the code adding a Thread.Sleep(10) like:

[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);
        }
    }

everything is fine, but we don't want to add a sleep to make everything working. Why such a behavior?

xpuser
  • 11
  • 2

0 Answers0