Luca
Luca

Reputation: 310

Why can't I delete a OneDrive sychronized folder with C#?

My problem is that I want to delete a folder created by myself in the OneDrive directory on the users' system. The directory you reach when entering "%OneDrive%" in the File Explorer, but I get an error:

System.IO.IOException: Access to the path '\?\C:\Users\user\OneDrive\Dokumente\Test\dc978eb5340c40d2887ad68fcd70a765' is denied.

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

I tried the following things:

All these attempts have the same outcome: the file gets deleted, the folder sticks around.

I can delete the folder manually in the file explorer.

Also, an important note is that if I disable the OneDrive sync everything gets deleted, it also works in non OneDrive directories.

I created a sample project where I can recreate the behavior:

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);
        }
    }
}

It's a basic Winforms application with a create and delete button. The File is a basic TXT file I added as an EmbeddedResource.

Edit 1: A simpler version of the above program as a console application:

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);
    }
}

The Path must be OneDrive Synchronized, the wait is necessary, because the error only occurs if the green checkmark from the OneDrive Sync is there. The Creation is part of the Problem, if the Folder was created by hand the Folder can be deleted.

Upvotes: 1

Views: 73

Answers (0)

Related Questions