1

In Windows if you are trying to replace a locked (in-use) file, technically it is possible to ask Windows to replace this file after OS restart.

My question: How can I do this programmatically in C#?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Rafael
  • 1,281
  • 2
  • 10
  • 35
  • 1
    No I don't think so. You could write a script and run it from the "run once" (set in the registry). – rory.ap Oct 05 '22 at 16:28
  • 1
    Yes you can in a number of different ways. – Robert McKee Oct 05 '22 at 16:52
  • 4
    The programmatic way is calling `MoveFileEx` with the `MOVEFILE_DELAY_UNTIL_REBOOT` flag. In C# this is done through P/Invoke, from Go this would be done through `syscall`. The caveat is that you can only do this as an administrator; if that's too much to ask for you have to roll your own mechanism through any of the many ways to automatically start programs. – Jeroen Mostert Oct 05 '22 at 17:16
  • 2
    If you trace that further down, there is another way as well. That call actually writes a special file that you technically can write to directly yourself (with elevated privs) to achieve the same thing, but the P/Invoke is much cleaner. – Robert McKee Oct 05 '22 at 18:25
  • 1
    https://stackoverflow.com/questions/721026/how-to-move-files-to-the-recycle-bin – Hans Passant Oct 05 '22 at 23:23
  • 1
    Does this answer your question? [Error when I want to delete file](/q/12120914/90527) – outis Oct 06 '22 at 07:27
  • @outis thank you, pinvoke was suggested by Robert McKee. Your link is helpful. Thanks. – Rafael Oct 06 '22 at 10:23

1 Answers1

1

It can be done via this approach:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
 

namespace ConsoleApplication1
{
    class Program
    {
        [Flags ]
        enum MoveFileFlags
        {
            MOVEFILE_REPLACE_EXISTING = 0x00000001,
            MOVEFILE_COPY_ALLOWED = 0x00000002,
            MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004,
            MOVEFILE_WRITE_THROUGH = 0x00000008,
            MOVEFILE_CREATE_HARDLINK = 0x00000010,
            MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x00000020
        }

        [DllImport ("kernel32.dll" , SetLastError = true , CharSet = CharSet .Unicode)]
        static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);

        static void Main(string [] args)
        {
            string fileName = @"e:\1.wav" ;

            MoveFileEx(fileName, null , MoveFileFlags .MOVEFILE_DELAY_UNTIL_REBOOT);
        }
    }
}

Source: https://social.msdn.microsoft.com/Forums/ja-JP/04a1e899-2a38-4d95-8ed5-6d53344e4d76/delete-locked-files-in-c?forum=csharplanguage

Thanks for insight to @Jeroen Mostert and @Robert McKee.

Rafael
  • 1,281
  • 2
  • 10
  • 35