若删除到回收站失败,会回退到永久删除
This commit is contained in:
1 parent
7f70c2e7f7
commit
f30c861f6e
2 files changed
+36
-11
No files matched your search
@@ -115,16 +115,28 @@ public static class DirectoryUtils {
|
||||
|
||||
/// <summary>
|
||||
/// 删除文件夹。
|
||||
/// <para/>若指定了 <paramref name="toRecycleBin"/>,则会尝试删除到回收站,但如果失败则会回退到永久删除。
|
||||
/// </summary>
|
||||
public static void Delete(string folder, bool toRecycleBin = false) {
|
||||
if (!DirectoryUtils.Exists(folder)) return;
|
||||
/// <returns>
|
||||
/// 如果文件夹不存在,返回 <see langword="null"/>。
|
||||
/// <para/>如果成功删除到回收站,返回 <see langword="true"/>。
|
||||
/// <para/>如果永久删除,返回 <see langword="false"/>。
|
||||
/// </returns>
|
||||
public static bool? Delete(string folder, bool toRecycleBin = false) {
|
||||
if (!DirectoryUtils.Exists(folder)) return null;
|
||||
Logger.Trace($"{(toRecycleBin ? "将文件夹删除到回收站" : "删除文件夹")}:{folder}");
|
||||
SafetyCheck(folder);
|
||||
// 删除
|
||||
// 删除到回收站
|
||||
if (toRecycleBin) {
|
||||
FileUtils.DeleteToRecycleBin(folder); // 删除到回收站
|
||||
} else {
|
||||
DeleteInternal(folder); // 永久删除
|
||||
try {
|
||||
FileUtils.DeleteToRecycleBin(folder);
|
||||
return true;
|
||||
} catch (Exception ex) {
|
||||
Logger.Warn(ex, $"无法将文件夹删除到回收站,回退到永久删除:{folder}");
|
||||
}
|
||||
}
|
||||
// 永久删除
|
||||
DeleteInternal(folder);
|
||||
static void DeleteInternal(string folder) {
|
||||
try {
|
||||
folder = PathUtils.ForApi(folder);
|
||||
@@ -140,7 +152,7 @@ public static class DirectoryUtils {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -176,16 +176,29 @@ public static class FileUtils {
|
||||
|
||||
/// <summary>
|
||||
/// 删除文件。
|
||||
/// <para/>若指定了 <paramref name="toRecycleBin"/>,则会尝试删除到回收站,但如果失败则会回退到永久删除。
|
||||
/// </summary>
|
||||
public static void Delete(string filePath, bool toRecycleBin = false) {
|
||||
if (!FileUtils.Exists(filePath)) return;
|
||||
/// <returns>
|
||||
/// 如果文件不存在,返回 <see langword="null"/>。
|
||||
/// <para/>如果成功删除到回收站,返回 <see langword="true"/>。
|
||||
/// <para/>如果永久删除,返回 <see langword="false"/>。
|
||||
/// </returns>
|
||||
public static bool? Delete(string filePath, bool toRecycleBin = false) {
|
||||
if (!FileUtils.Exists(filePath)) return null;
|
||||
Logger.Trace($"{(toRecycleBin ? "将文件删除到回收站" : "删除文件")}:{filePath}");
|
||||
// 删除到回收站
|
||||
if (toRecycleBin) {
|
||||
try {
|
||||
DeleteToRecycleBin(filePath);
|
||||
} else {
|
||||
return true;
|
||||
} catch (Exception ex) {
|
||||
Logger.Warn(ex, $"无法将文件删除到回收站,回退到永久删除:{filePath}");
|
||||
}
|
||||
}
|
||||
// 永久删除
|
||||
ResilientUtils.RetryOn<IOException>(()
|
||||
=> File.Delete(PathUtils.ForApi(filePath)));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user