Robert E. McIntosh
Robert E. McIntosh

Reputation: 6135

C# Directory.Delete Throwing Illegal Character Error

So we have an application where users keep losing their toolbars and the only way to fix the issue is to delete a folder in the appdata for that user. So we wrote a simple little program that deletes this folder here is the error we are getting in the try catch

System.ArgumentException: Illegal characters in path.
   at System.IO.Path.CheckInvalidPathChars(String path)
   at System.IO.Path.InternalCombine(String path1, String path2)
   at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive)
   at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive)
   at System.IO.Directory.Delete(String path, Boolean recursive)
   at DeleteFolder.frnDeleteFolder.btnDelete_Click(Object sender, EventArgs e) in C:\Users\rmcintosh.K12.000\documents\visual studio 2010\Projects\DeleteFolder\DeleteFolder\frnDeleteFolder.cs:line 82

Here is the code we are using to delete

   string path = @"C:\Users\98532153\AppData\Roaming\DraftSight";
    try
    {
        if (Directory.Exists(path)) {
            Directory.Delete(path, true);
        }
        else
        {
            MessageBox.Show("Directory Does Not Exists");
        }

    }
    catch (Exception ex)
    {
        richTextBox1.Text = ex.ToString();
    }

I would like to point out this works find as long as the main directory is empty, but as soon as I add any file subdirectory it throws this error.

Upvotes: 0

Views: 384

Answers (3)

Roger Lipscombe
Roger Lipscombe

Reputation: 91825

Backslash in a C# string is an escape character; you either need string path = @"C:\Whatever\Wherever"; -- note the '@' -- or you need string path = "C:\\Whatever\\Wherever"; -- note the double-backslashes.

You can read more about string literals on MSDN.

Upvotes: 3

Lawrence Thurman
Lawrence Thurman

Reputation: 677

if you look at the Intellisense in VS it tells you that the directory must be empty.

call Directory.GetFiles and purge them thendelete the directory.

if you need I can help you with a recursive method to do this.

Upvotes: 0

Cinchoo
Cinchoo

Reputation: 6322

Looks like some sub-directories deep inside may have some invalid characters in their names. Somehow .NET not handling it. Only way is to write your own routine, check the path recursively and delete them.

Upvotes: 0

Related Questions