none
Unable to delete an open folder. RRS feed

  • Question

  • I have a program that creates a work folder on C:\ (yeah, I know, bad practice) when it starts.

    I need to be able to delete the work folder if the user starts a new project but I can't b/c I get a "file in use" error.

    Is there a simple fix?

    If FileIO.FileSystem.DirectoryExists("c:\UserWork") Then
       ' Must close link to open folder before we can delete it.
       ' {Missing code will go here.}
    ...
    
       FileIO.FileSystem.DeleteDirectory("c:\UserWork", _
        FileIO.DeleteDirectoryOption.DeleteAllContents) ' Start fresh
    End If
    FileIO.FileSystem.CreateDirectory("c:\UserWork")
    FileIO.FileSystem.CreateDirectory(strTemp) ' strTemp preset to "c:\UserWork\Data"
    

    TIA

    Friday, April 20, 2018 6:08 PM

Answers

  • You can't delete the file until it's in use...

    .
    That seems backwards. I think you mean "while" in use because that's the error I'm getting.

    I went through my code line-by-line (trying to manually delete the folder each time) and discovered the problem appears right after I set the ".CurrentDirectory" to my work folder. It can't be deleted as long as it is the current directory. (Yeah, I feel dumb. But no one else noticed either.)

    Removing "My.Computer.FileSystem.CurrentDirectory = strTemp" gets me past the "File In Use" error, but now I must go through and edit all my paths. :P

    Saturday, April 21, 2018 12:37 PM

All replies

  • File in use inside the work folder? You can't delete a folder if a file within the folder is in use I suppose. And you can't delete a file in use. I suppose there's API's to detect what is locking the file then kill the app locking the file maybe.

    La vida loca

    • Edited by Mr. Monkeyboy Friday, April 20, 2018 6:40 PM
    • Proposed as answer by Cor Ligthert Saturday, April 21, 2018 7:44 AM
    • Unproposed as answer by Cor Ligthert Saturday, April 21, 2018 9:38 AM
    Friday, April 20, 2018 6:37 PM
  • File in use inside the work folder? You can't delete a folder if a file within the folder is in use I suppose. And you can't delete a file in use. I suppose there's API's to detect what is locking the file then kill the app locking the file maybe.


    Thx for the reply.

    I get the error even if there are no files (just folders) inside the work folder. :(


    PS: Like your icon. :D
    Friday, April 20, 2018 6:54 PM
  • File in use inside the work folder? You can't delete a folder if a file within the folder is in use I suppose. And you can't delete a file in use. I suppose there's API's to detect what is locking the file then kill the app locking the file maybe.


    Thx for the reply.

    I get the error even if there are no files (just folders) inside the work folder. :(


    PS: Like your icon. :D

    Can you delete a sub folder? If so, then try deleting the subfolders first (recursively) and then delete the parent.

    For Each d in Directory.GetDirectories("c:\UserWork")
        Directory.Delete(d, true)
    Next
    


    Paul ~~~~ Microsoft MVP (Visual Basic)

    Friday, April 20, 2018 7:16 PM
  • I have a program that creates a work folder on C:\ (yeah, I know, bad practice) when it starts.

    I need to be able to delete the work folder if the user starts a new project but I can't b/c I get a "file in use" error.

    Is there a simple fix?

    If FileIO.FileSystem.DirectoryExists("c:\UserWork") Then
       ' Must close link to open folder before we can delete it.
       ' {Missing code will go here.}
    ...
    
       FileIO.FileSystem.DeleteDirectory("c:\UserWork", _
        FileIO.DeleteDirectoryOption.DeleteAllContents) ' Start fresh
    End If
    FileIO.FileSystem.CreateDirectory("c:\UserWork")
    FileIO.FileSystem.CreateDirectory(strTemp) ' strTemp preset to "c:\UserWork\Data"

    TIA

    If the file is open then you can't delete the folder.  In this test the file is closed after it is created.

            Dim tmpD As String = IO.Path.GetTempPath
            tmpD = IO.Path.Combine(tmpD, "UserWork")
    
            If Not IO.Directory.Exists(tmpD) Then
                IO.Directory.CreateDirectory(tmpD)
            End If
    
            'create some files
            Dim fns() As String = {"one.txt", "two.txt"}
    
            For Each fn As String In fns
                Dim tmpf As String = IO.Path.Combine(tmpD, fn)
                If Not IO.File.Exists(tmpf) Then
                    Dim ios As IO.FileStream = IO.File.Create(tmpf)
                    ' so folder can be deleted
                    ios.Close() 'close the stream
                    ios.Dispose() '  and dispose
                End If
            Next
    
            IO.Directory.Delete(tmpD, True)
    


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it."

    - from former MSDN User JohnWein

    SerialPort Info

    Multics - An OS ahead of its time.

    Friday, April 20, 2018 7:22 PM
  • Can you delete a sub folder? If so, then try deleting the subfolders first (recursively) and then delete the parent.

    The "DeleteAllContents" parameter in my delete command would take care of that.
    Friday, April 20, 2018 7:48 PM
  • If the file is open then you can't delete the folder.  In this test the file is closed after it is created.


    Thx, but as noted above, I get the error even when all it contains are empty folders. :(
    Friday, April 20, 2018 7:50 PM
  • Can you delete a sub folder? If so, then try deleting the subfolders first (recursively) and then delete the parent.


    The "DeleteAllContents" parameter in my delete command would take care of that.

    Then I suspect you will need to find out which process has the folder open. You don't have it open in Windows Explorer by any chance?

    If your app has it open then it sounds like a file or folder was not closed and there is open file handle remaining.


    Paul ~~~~ Microsoft MVP (Visual Basic)

    • Proposed as answer by Cor Ligthert Saturday, April 21, 2018 7:45 AM
    • Unproposed as answer by Cor Ligthert Saturday, April 21, 2018 9:38 AM
    Friday, April 20, 2018 8:05 PM
  • Well can you manually delete the folder and all folders in it just not programmatically?

    La vida loca

    • Proposed as answer by Cor Ligthert Saturday, April 21, 2018 7:45 AM
    • Unproposed as answer by Cor Ligthert Saturday, April 21, 2018 9:38 AM
    Friday, April 20, 2018 11:34 PM
  • Well can you manually delete the folder and all folders in it just not programmatically?

    When the program is not running, yes. If the program is running, I get the same error in Windows when trying to delete it manually from the File Explorer.
    Friday, April 20, 2018 11:52 PM
  • Well can you manually delete the folder and all folders in it just not programmatically?



    When the program is not running, yes. If the program is running, I get the same error in Windows when trying to delete it manually from the File Explorer.

    Is there any code between checking whether the file exists and attempting to delete the folder/subfolders? I'm assuming there is no code before this that accesses the folder in question.

    I've tested the code you have and it works fine for me, so there must be something in your code or declared in your app that is referencing a file, the folder or a subfolder.


    Paul ~~~~ Microsoft MVP (Visual Basic)

    Saturday, April 21, 2018 12:37 AM
  • BTW, you may want to consider using the Process Monitor utility to troubleshoot the issue.

    https://docs.microsoft.com/en-us/sysinternals/downloads/procmon


    Paul ~~~~ Microsoft MVP (Visual Basic)

    Saturday, April 21, 2018 12:40 AM
  • Well can you manually delete the folder and all folders in it just not programmatically?



    When the program is not running, yes. If the program is running, I get the same error in Windows when trying to delete it manually from the File Explorer.

    What are the files in the folders and can you show the code that you create the files with?

    Do you have disc image references open like in the icon explorer from this thread?

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/963de576-cb11-492c-9a99-02091b907cf3/cant-overwrite-a-file-file-in-use-by-my-program-how-do-i-fix?forum=vbgeneral

    Saturday, April 21, 2018 12:48 AM
  • Well can you manually delete the folder and all folders in it just not programmatically?



    When the program is not running, yes. If the program is running, I get the same error in Windows when trying to delete it manually from the File Explorer.

    Without seeing the code on how you are dealing with folders and files and why your app is locking folders I do not know how to assist. But I suspect you aren't disposing of some object possibly causing the lock issue.


    La vida loca

    Saturday, April 21, 2018 2:00 AM
  • Is there any code between checking whether the file exists and attempting to delete the folder/subfolders? I'm assuming there is no code before this that accesses the folder in question.

    I've tested the code you have and it works fine for me, so there must be something in your code or declared in your app that is referencing a file, the folder or a subfolder.


    No omitted code *within* the provided clip, but error does not occur until the routine is called the *second* time (when the user tries to start a "New" project and I attempt to delete the existing Work folder.)
    Saturday, April 21, 2018 2:05 AM
  • What are the files in the folders and can you show the code that you create the files with?

    Do you have disc image references open like in the icon explorer from this thread?


    The folders can be completely empty and the error still occurs.

    The code that creates the folders is the code I posted above.

    The first time through, the Work folder is created, I use "FileIO.FileSystem.FileExists(...)" to see if an archive is present elsewhere and if so, extract it to the folder.

    But even when no archive exists and nothing is extracted to the Work folder, I still can't delete it.

    Saturday, April 21, 2018 2:23 AM
  • BTW, you may want to consider using the Process Monitor utility


    The Process locking my folder is my program.
    Saturday, April 21, 2018 2:24 AM
  • I have a program that creates a work folder on C:\ (yeah, I know, bad practice) when it starts.

    I need to be able to delete the work folder if the user starts a new project but I can't b/c I get a "file in use" error.

    Is there a simple fix?

    If FileIO.FileSystem.DirectoryExists("c:\UserWork") Then
       ' Must close link to open folder before we can delete it.
       ' {Missing code will go here.}
    ...
    
       FileIO.FileSystem.DeleteDirectory("c:\UserWork", _
        FileIO.DeleteDirectoryOption.DeleteAllContents) ' Start fresh
    End If
    FileIO.FileSystem.CreateDirectory("c:\UserWork")
    FileIO.FileSystem.CreateDirectory(strTemp) ' strTemp preset to "c:\UserWork\Data"

    TIA

    Well this code works. On the other hand it will create "C:\UserWork\Data" if just the second line in Button1 is used. It removes the "UserWork" and sub directory with no problems.

        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            IO.Directory.CreateDirectory("c:\UserWork")
            IO.Directory.CreateDirectory("c:\UserWork\Data")
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            IO.Directory.Delete("c:\UserWork", True)
        End Sub


    La vida loca

    Saturday, April 21, 2018 3:42 AM
  • Without seeing the code on how you are dealing with folders and files and why your app is locking folders I do not know how to assist.

    ' This is the next thing after creating the Work folder the first time.
    If FileIO.FileSystem.FileExists(Source) then ' "Source" is an archive file.
       My.Computer.FileSystem.CurrentDirectory = strTemp ' The Work folder
    myCodec(strDirection, Source, Dest) ' "Dest" is a folder inside StrTemp.
    FileIO.FileSystem.CopyFile("archive.cab", "archive.bkp")
    FileIO.FileSystem.DeleteFile("archive.bkp") ' Delete copy of original
    ' to the Recycle Bin as insurance.
    End If
    .
    If an archive exists, its contents are extracted to the Dest folder. A copy of the archive is made before working on it and deleted to the Recycle Bin (in case the user makes a mistake and needs the original back.)

    If there is no Source file, the "If" condition is not met and nothing is ever extracted to the Dest folder. Yet I'm still being told the "File [my empty folder] is in use" when I try to delete it to start a New project.

    I'm thinking that instead of using "My.Computer" or "FileIO.FileSystem", if I could do the same thing using "FileStream", I'd at least have access to the ".Close()" command, but I'm having trouble implementing it.

    Saturday, April 21, 2018 3:56 AM
  • I don't know what myCodec does.

    Regardless there are other methods. I've never used FiloIO but I can't see why it would lock any folders or files I suppose. I still think it's something else in your app locking the folders but maybe not.

    File.Copy Method

    File.Move Method (String, String)

    File.Exists Method (String)

    File.Delete Method (String)

    Directory.Delete Method (String, Boolean) - Deletes the specified directory and, if indicated, any subdirectories and files in the directory.


    La vida loca

    Saturday, April 21, 2018 4:06 AM
  • BTW, you may want to consider using the Process Monitor utility


    The Process locking my folder is my program.

    Then you will probably need to use the Process Monitor utility to find out when there is an open on the folder by your app. I would suspect that this will require stepping through the code in debug - somewhat tedious but you should be able to identify when it occurs so that the code can be changed.

    Paul ~~~~ Microsoft MVP (Visual Basic)

    Saturday, April 21, 2018 4:07 AM
  • Well this code works. On the other hand it will create "C:\UserWork\Data" if just the second line in Button1 is used.
    .
    Thx, but as noted earlier, my code works the first time through, but not the second (when the user tries to start over with a New project.)

    I try to delete the Work folder... empty or not... and recreate it. But the program won't let me, claiming the "File" (my folder) is still in use.

    I don't know if it matters, but I noticed your "Click" action doesn't check to see if the folder exists before trying to delete it.
    Saturday, April 21, 2018 4:24 AM
  • You can't delete the file until it's in use...try this sample in my case its work for me 

    protected virtual bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            //the file is unavailable because it is:
            //still being written to
            //or being processed by another thread
            //or does not exist (has already been processed)
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }


    FileInfo file = new FileInfo("PathToTheFile");
    while (IsFileLocked(file))
        Thread.Sleep(1000);
    file.Delete();

    Saturday, April 21, 2018 4:42 AM
  • That is most probably because the methods you use don't direct flush the buffers (DeletAllContents) maybe it will go if you delete the files one by one likewise as I thought to have seen in this thread.

    Look for a description of your problem on this page

    https://msdn.microsoft.com/en-us/library/windows/desktop/aa364439(v=vs.85).aspx

     

    Success
    Cor



    Saturday, April 21, 2018 9:37 AM
  • Process Monitor can be difficult to use because it generates a large amount of data.  However, to find open files and directories you can use the Microsoft Sysinternals' Handle utility.

    For example, to find the processes holding open C:\UserWork at a command line prompt you would enter the command -

    Handle C:\UserWork

    • Edited by RLWA32 Saturday, April 21, 2018 12:00 PM
    Saturday, April 21, 2018 11:58 AM
  • You can't delete the file until it's in use...

    .
    That seems backwards. I think you mean "while" in use because that's the error I'm getting.

    I went through my code line-by-line (trying to manually delete the folder each time) and discovered the problem appears right after I set the ".CurrentDirectory" to my work folder. It can't be deleted as long as it is the current directory. (Yeah, I feel dumb. But no one else noticed either.)

    Removing "My.Computer.FileSystem.CurrentDirectory = strTemp" gets me past the "File In Use" error, but now I must go through and edit all my paths. :P

    Saturday, April 21, 2018 12:37 PM
  • You can't delete the file until it's in use...

    .
    That seems backwards. I think you mean "while" in use because that's the error I'm getting.

    I went through my code line-by-line (trying to manually delete the folder each time) and discovered the problem appears right after I set the ".CurrentDirectory" to my work folder. It can't be deleted as long as it is the current directory. (Yeah, I feel dumb. But no one else noticed either.)

    Removing "My.Computer.FileSystem.CurrentDirectory = strTemp" gets me past the "File In Use" error, but now I must go through and edit all my paths. :P

    This is why it's good to post all code that has anything to do with the issue. Also it's extremely rare to set the CurrentDirectory. I've done more file I/O work in thirty years that I could possible remember and never needed to set current directory.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, April 21, 2018 12:50 PM
    Moderator
  • You can't delete the file until it's in use...

    .
    That seems backwards. I think you mean "while" in use because that's the error I'm getting.

    I went through my code line-by-line (trying to manually delete the folder each time) and discovered the problem appears right after I set the ".CurrentDirectory" to my work folder. It can't be deleted as long as it is the current directory. (Yeah, I feel dumb. But no one else noticed either.)

    Removing "My.Computer.FileSystem.CurrentDirectory = strTemp" gets me past the "File In Use" error, but now I must go through and edit all my paths. :P

    No one noticed that you set the current directory to your work folder because you didn't post that code. :-p

    This is why you needed to step through your code in debug and try to identify when the folder was actually considered open.


    Paul ~~~~ Microsoft MVP (Visual Basic)

    Saturday, April 21, 2018 12:52 PM
  • Process Monitor can be difficult to use because it generates a large amount of data.  However, to find open files and directories you can use the Microsoft Sysinternals' Handle utility.

    For example, to find the processes holding open C:\UserWork at a command line prompt you would enter the command -

    Handle C:\UserWork


    That's why Process Monitor has filtering capabilities. At a minimum you can filter the messages for your process and then work from there. It's not that difficult to use.

    Paul ~~~~ Microsoft MVP (Visual Basic)

    Saturday, April 21, 2018 12:57 PM
  • That's why Process Monitor has filtering capabilities. At a minimum you can filter the messages for your process and then work from there. It's not that difficult to use.

    I'm aware of the filtering.

    For a limited usage (and perhaps limited experience with Procmon) scenario, the purpose-built functionality of Handle seemed to me to be an easier alternative.

    With experience, either utility would suffice.



    • Edited by RLWA32 Saturday, April 21, 2018 1:23 PM
    Saturday, April 21, 2018 1:22 PM
  • No one noticed that you set the current directory to your work folder because you didn't post that code. :-p
    .
    I did, but a few posts later in my reply to "Mr. Monkeyboy" where he asked to see the code where I "deal with folders" (after my error so I didn't think to originally include it, not realizing the error was taking place on the second pass.)

    Unfortunately, the entire program is too extensive to have posted the entire thing.
    Saturday, April 21, 2018 1:45 PM
  • You can't delete the file until it's in use...try this sample in my case its work for me 

    protected virtual bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            //the file is unavailable because it is:
            //still being written to
            //or being processed by another thread
            //or does not exist (has already been processed)
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }


    FileInfo file = new FileInfo("PathToTheFile");
    while (IsFileLocked(file))
        Thread.Sleep(1000);
    file.Delete();

    Since this forum for VB.NET in the future only post VB.NET code, never assume whomever is asking a question will even want to try using a language converter. If posted by mistake e.g. C# in this forum that indicate this (I've done so and admitted to it).

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, April 21, 2018 1:48 PM
    Moderator

  • No one noticed that you set the current directory to your work folder because you didn't post that code. :-p


    Paul, 

    That is what I thought as well, but it is, I used a find to check it.

    :-)

    However, it makes it not as clear as Mugsy wanted us to believe but whatever.


    Success
    Cor

    Saturday, April 21, 2018 1:50 PM
  • I've tested the code you have and it works fine for me, so there must be something in your code or declared in your app that is referencing a file, the folder or a subfolder.


    Paul ~~~~ Microsoft MVP (Visual Basic)

    No omitted code *within* the provided clip,

    Mugsy_in_Houston

    I still think it's something else in your app locking the folders but maybe not.

    @ Mugsy_in_Houston

    If we can't see the omitted code then we can't obviously attempt to understand the problem. It is nice to know that setting the apps working path (current directory) can cause this problem!!!


    La vida loca

    Saturday, April 21, 2018 6:38 PM