In my WebApi
action method, I want to create/over-write a folder using this code:
string myDir = \"...\";
if(Directory.Exists(myDir))
{
Dir
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.