Using Directory.Delete() and Directory.CreateDirectory() to overwrite a folder

后端 未结 3 1737
走了就别回头了
走了就别回头了 2021-01-01 23:29

In my WebApi action method, I want to create/over-write a folder using this code:

string myDir = \"...\";
if(Directory.Exists(myDir)) 
{
    Dir         


        
3条回答
  •  孤城傲影
    2021-01-02 00:20

    I wrote myself a little C# method for synchronous folder deletion using Directory.Delete(). Feel free to copy:

    private bool DeleteDirectorySync(string directory, int timeoutInMilliseconds = 5000)
    {
        if (!Directory.Exists(directory))
        {
            return true;
        }
    
        var watcher = new FileSystemWatcher
        {
            Path = Path.Combine(directory, ".."),
            NotifyFilter = NotifyFilters.DirectoryName,
            Filter = directory,
        };
        var task = Task.Run(() => watcher.WaitForChanged(WatcherChangeTypes.Deleted, timeoutInMilliseconds));
    
        // we must not start deleting before the watcher is running
        while (task.Status != TaskStatus.Running)
        {
            Thread.Sleep(100);
        }
    
        try
        {
            Directory.Delete(directory, true);
        }
        catch
        {
            return false;
        }
    
        return !task.Result.TimedOut;
    }
    

    Note that getting task.Result will block the thread until the task is finished, keeping the CPU load of this thread idle. So that is the point where it gets synchronous.

提交回复
热议问题