Why is access to the path denied?

前端 未结 29 1642
刺人心
刺人心 2020-11-22 15:25

I am having a problem where I am trying to delete my file but I get an exception.

if (result == \"Success\")
{
     if (FileUpload.HasFile)
     {
         t         


        
29条回答
  •  星月不相逢
    2020-11-22 15:44

    In my particular case I was repeatedly creating and deleting 10000 folders. It seems to me that the problem was in that although the method Directory.Delete(path, true) returns, the underling OS mechanism may still be deleting the files from the disk. And when I am starting to create new folders immediately after deletion of old ones, some of them are still locked because they are not completely deleted yet. And I am getting System.UnauthorizedAccessException: "Access to the path is denied".

    Using Thread.Sleep(5000) after Directory.Delete(path, true) solves that problem. I absolutely agree that this is not safe, and I am not encouraging anyone to use it. I would love to here a better approach to solve this problem to improve my answer. Now I am just giving an idea why this exception may happen.

    class Program
    {
        private static int numFolders = 10000;
        private static string rootDirectory = "C:\\1";
    
        static void Main(string[] args)
        {
            if (Directory.Exists(rootDirectory))
            {
                Directory.Delete(rootDirectory, true);
                Thread.Sleep(5000);
            }
    
            Stopwatch sw = Stopwatch.StartNew();
            CreateFolder();
            long time = sw.ElapsedMilliseconds;
    
            Console.WriteLine(time);
            Console.ReadLine();
        }
    
        private static void CreateFolder()
        {
            var one = Directory.CreateDirectory(rootDirectory);
    
            for (int i = 1; i <= numFolders; i++)
            {
                one.CreateSubdirectory(i.ToString());
            }
        }
    }
    

提交回复
热议问题