“the process cannot access the file because it is being used by another process” when trying to delete file

前端 未结 4 1192

when deleting files one by one error is generated as \"the process cannot access the file \' because it is being used by another process when trying to delete file\"

cod

相关标签:
4条回答
  • 2021-01-21 19:10

    If the file is in use you cannot delete it. However, if you for some reason really want to delete it and you are unable to stop the process that is locking the file (like when uninstalling an application) you can schedule the file for deletion the next time the operating system is restarted. These scheduled deletions are performed before any process is able to lock the file.

    You have to use the MoveFileEx Windows API using a null new file name and the flag MOVEFILE_DELAY_UNTIL_REBOOT. How to do that from C# is explained in an answer to the Stack Overflow question “MoveFile” function in C# (Delete file after reboot) C#.

    0 讨论(0)
  • 2021-01-21 19:11

    You don't say specifically what file you're trying to delete, but from your question it sounds like you're trying to delete the image file that you loaded. If that's the case, then you have a problem. The documentation for Image.FromFile says:

    The file remains locked until the Image is disposed.

    If you need the ability to delete the file, you'll want to copy the image after you've loaded it, and use that image in your PictureBox. Then you can dispose the loaded image, thereby unlocking the file.

    0 讨论(0)
  • 2021-01-21 19:21

    You will not be able to delete any file when is is locked by another process.

    You first have to find out which process locks the file.
    This is possible with SysInternals ProcessExplorer. Use the "Find handle or DLL" function.

    0 讨论(0)
  • 2021-01-21 19:34
    pb.Image.Dispose();
    pb.Dispose();
    

    After steps above, tou can use picture again

    0 讨论(0)
提交回复
热议问题