Directory.Delete gives error Part of the path is not found

Peter Karlström 216 Reputation points
2020-10-25T21:26:15.013+00:00

Hello
In my application a want to delete files and folders from some specific root paths before backing up files to these destinations.

For each subfolder in the root paths, I use the command Directory.Delete(<subfolder>, True) from System.IO.

Most of the directories are deleted but some of them generates these errors:
"part of the path could not be found" and HResult -2147024893.

The left files and folders are not write protected or owned by any other account than the rest of the files/folders.
I have no problems deleting the left folders manually with the same user profile that runs the application.

The application is developed in Visual Studio 2017 on .NET Framework 4.7.2 and is executed as a scheduled task running in 64-bit mode.

Whats seems to be the problem here?
Does anybody has a clue?

Regards
Peter Karlström
Sweden

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,096 questions
{count} votes

Accepted answer
  1. Castorix31 85,116 Reputation points
    2020-11-08T08:50:12.997+00:00

    As suggested in comments, you can do a test with SHFileOperation to check if you get the same error
    If it works, you could replace it by IFileOperation, although SHFileOperation should still be available for a long time...
    =>

    // Change the path...
    string sSource = @"E:\Temp\Test";
    var fos = new SHFILEOPSTRUCT
    {
        wFunc = FO.FO_DELETE,
        pFrom = sSource + '\0',
        pTo = null,
        fFlags = FILEOP_FLAGS.FOF_NOCONFIRMATION | FILEOP_FLAGS.FOF_SILENT
        //fFlags = FILEOP_FLAGS.FOF_ALLOWUNDO // move to Recycle Bin for test
    };
    try
    {
        int nReturn = SHFileOperation(ref fos);
        if (nReturn != 0)
            throw new Win32Exception(nReturn);
    }
    catch (Win32Exception w)
    {
        System.Windows.Forms.MessageBox.Show("Error : " + w.NativeErrorCode.ToString() + "\n" + w.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    

    Declarations :

    public enum FO : int
    {
        FO_MOVE = 0x0001,
        FO_COPY = 0x0002,
        FO_DELETE = 0x0003,
        FO_RENAME = 0x0004
    }
    
    [Flags]
    public enum FILEOP_FLAGS : uint
    {
        FOF_MULTIDESTFILES = 0x0001,
        FOF_CONFIRMMOUSE = 0x0002,
        FOF_SILENT = 0x0004,  // don't create progress/report
        FOF_RENAMEONCOLLISION = 0x0008,
        FOF_NOCONFIRMATION = 0x0010,  // Don't prompt the user.
        FOF_WANTMAPPINGHANDLE = 0x0020,  // Fill in SHFILEOPSTRUCT.hNameMappings
                                         // Must be freed using SHFreeNameMappings
        FOF_ALLOWUNDO = 0x0040,
        FOF_FILESONLY = 0x0080,  // on *.*, do only files
        FOF_SIMPLEPROGRESS = 0x0100,  // means don't show names of files
        FOF_NOCONFIRMMKDIR = 0x0200,  // don't confirm making any needed dirs
        FOF_NOERRORUI = 0x0400,  // don't put up error UI
        FOF_NOCOPYSECURITYATTRIBS = 0x0800,  // dont copy NT file Security Attributes
        FOF_NORECURSION = 0x1000,  // don't recurse into directories.
        FOF_NO_CONNECTED_ELEMENTS = 0x2000,  // don't operate on connected file elements.
        FOF_WANTNUKEWARNING = 0x4000,  // during delete operation, warn if nuking instead of recycling (partially overrides FOF_NOCONFIRMATION)
        FOF_NORECURSEREPARSE = 0x8000,  // treat reparse points as objects, not containers
    
        FOFX_NOSKIPJUNCTIONS = 0x00010000,  // Don't avoid binding to junctions (like Task folder, Recycle-Bin)
        FOFX_PREFERHARDLINK = 0x00020000,  // Create hard link if possible
        FOFX_SHOWELEVATIONPROMPT = 0x00040000,  // Show elevation prompts when error UI is disabled (use with FOF_NOERRORUI)
        FOFX_EARLYFAILURE = 0x00100000,  // Fail operation as soon as a single error occurs rather than trying to process other items (applies only when using FOF_NOERRORUI)
        FOFX_PRESERVEFILEEXTENSIONS = 0x00200000,  // Rename collisions preserve file extns (use with FOF_RENAMEONCOLLISION)
        FOFX_KEEPNEWERFILE = 0x00400000,  // Keep newer file on naming conflicts
        FOFX_NOCOPYHOOKS = 0x00800000,  // Don't use copy hooks
        FOFX_NOMINIMIZEBOX = 0x01000000,  // Don't allow minimizing the progress dialog
        FOFX_MOVEACLSACROSSVOLUMES = 0x02000000,  // Copy security information when performing a cross-volume move operation
        FOFX_DONTDISPLAYSOURCEPATH = 0x04000000,  // Don't display the path of source file in progress dialog
        FOFX_DONTDISPLAYDESTPATH = 0x08000000,  // Don't display the path of destination file in progress dialog
    }
    
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
    public struct SHFILEOPSTRUCT
    {
        public IntPtr hwnd;
        [MarshalAs(UnmanagedType.U4)]
        public FO wFunc;
        public string pFrom;
        public string pTo;
        public FILEOP_FLAGS fFlags;
        [MarshalAs(UnmanagedType.Bool)]
        public bool fAnyOperationsAborted;
        public IntPtr hNameMappings;
        public string lpszProgressTitle;
    }
    
    [DllImport("Shell32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "SHFileOperationW")]
    public static extern int SHFileOperation(ref SHFILEOPSTRUCT lpFileOp);
    

1 additional answer

Sort by: Most helpful
  1. Yan Gu - MSFT 2,676 Reputation points
    2020-10-26T05:41:19.817+00:00

    Hello, @Peter Karlström
    Welcome to Microsoft Q&A!

    Currently, Microsoft Q&A supports the products listed over here: supported topics (more to be added later on).

    Your question about .NET APIs is not supported yet now. The support team is actively answer questions about .NET API in the MSDN Forum. You could ask this question in the MSDN Visual C# forum.

    Thank you.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.