public void DeleteFile(string path, DeletionOptions options) { options = options ?? DeletionOptions.TryThreeTimes; if (string.IsNullOrWhiteSpace(path)) { return; } var firstAttemptFailed = false; for (var i = 0; i < options.RetryAttempts; i++) { try { if (File.Exists(path)) { if (firstAttemptFailed) { File.SetAttributes(path, FileAttributes.Normal); } File.Delete(path); return; } } catch { Thread.Sleep(options.SleepBetweenAttemptsMilliseconds); firstAttemptFailed = true; if (i == options.RetryAttempts - 1) { if (options.ThrowOnFailure) { throw; } break; } } } }
public void DeleteDirectory(string path, DeletionOptions options) { options = options ?? DeletionOptions.TryThreeTimes; if (string.IsNullOrWhiteSpace(path)) { return; } for (var i = 0; i < options.RetryAttempts; i++) { try { var dir = new DirectoryInfo(path); if (dir.Exists) { dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; dir.Delete(true); return; } } catch { Thread.Sleep(options.SleepBetweenAttemptsMilliseconds); if (i == options.RetryAttempts - 1) { if (options.ThrowOnFailure) { throw; } break; } } } }