为何无法用C#删除OneDrive同步文件夹?
我需要删除用户OneDrive目录(文件资源管理器输入%OneDrive%可访问)下自行创建的文件夹,但遇到权限拒绝错误:
System.IO.IOException: 对路径'?\C:\Users\user\OneDrive\Dokumente\Test\dc978eb5340c40d2887ad68fcd70a765'的访问被拒绝。
调用栈信息:
at System.IO.FileSystem.RemoveDirectoryInternal(String fullPath, Boolean topLevel, Boolean allowDirectoryNotEmpty)
at System.IO.FileSystem.RemoveDirectoryRecursive(String fullPath, WIN32_FIND_DATA& findData, Boolean topLevel)
at System.IO.FileSystem.RemoveDirectory(String fullPath, Boolean recursive)
at System.IO.DirectoryInfo.Delete(Boolean recursive)
at ExampleOnedriveError.Form1.deleteButton_Click(Object sender, EventArgs e) in C:\projects\cmi\ExampleOnedriveError\ExampleOnedriveError\Form1.cs:line 47
已尝试的解决方案
- 手动修改目录权限,允许所有人删除
- 以管理员身份运行应用
- 将目录移动至非OneDrive同步目录
- 不带递归标志逐个删除文件和文件夹
- 每200ms重试删除,持续2秒
所有尝试均得到同一结果:文件可删除,但文件夹残留。手动在文件资源管理器中可删除该文件夹。重要提示:禁用OneDrive同步后可正常删除,非OneDrive目录下也可正常操作。
可复现问题的示例代码
WinForms版本
public partial class Form1 : Form { private static DirectoryInfo info; private static string FILE_NAME = "bbb.txt"; public Form1() { InitializeComponent(); } private void createFolder_Click(object sender, EventArgs e) { var currentDirectory = AppDomain.CurrentDomain.BaseDirectory; var sourceFile = Path.Combine(currentDirectory, FILE_NAME); if (!File.Exists(sourceFile)) { Console.WriteLine("Error: Source file not found."); return; } var oneDrivePath = Environment.GetEnvironmentVariable("OneDrive"); if (string.IsNullOrEmpty(oneDrivePath)) { Console.WriteLine("Error: OneDrive environment variable is not set."); return; } var newDirectory = Path.Combine(oneDrivePath, "Dokumente", "Test", Guid.NewGuid().ToString("N")); info = Directory.CreateDirectory(newDirectory); var destinationFile = Path.Combine(newDirectory, FILE_NAME); File.Copy(sourceFile, destinationFile); Console.WriteLine($"File copied successfully to: {destinationFile}"); } private void deleteButton_Click(object sender, EventArgs e) { try { info.Delete(true); } catch (Exception exception) { Console.WriteLine(exception); } } }
这是一个带有创建和删除按钮的基础WinForms应用,文件是添加为EmbeddedResource的基础TXT文件。
控制台应用版本(编辑1)
public class Example { public static async Task Main(string[] args) { const string dir = @"C:\Users\user\OneDrive\Dokumente\Test\95b5d15b41ca42eea0b2b969a8b0dcd7\"; const string fileTxt = "file.txt"; Directory.CreateDirectory(dir); var destFileName = Path.Combine(dir, fileTxt); await using (var writer = File.CreateText(destFileName)) { await writer.WriteLineAsync("Hello, World!"); } await Task.Delay(10000); Directory.Delete(dir, true); } }
路径必须为OneDrive同步目录,等待操作是必要的,因为仅当OneDrive同步出现绿色对勾时才会触发错误。创建操作是问题的一部分:手动创建的文件夹可正常删除。
内容的提问来源于stack exchange,提问作者Luca

