"Movefile" Function in C# (Delete File After Reboot)

MoveFile function in C# (Delete file after reboot)

You'll need the P/Invoke declarations for MoveFileEx:

[Flags]
internal enum MoveFileFlags
{
None = 0,
ReplaceExisting = 1,
CopyAllowed = 2,
DelayUntilReboot = 4,
WriteThrough = 8,
CreateHardlink = 16,
FailIfNotTrackable = 32,
}

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

And some example code:

if (!NativeMethods.MoveFileEx("a.txt", null, MoveFileFlags.DelayUntilReboot))
{
Console.Error.WriteLine("Unable to schedule 'a.txt' for deletion");
}

File.Move fails when preceded by a File.Delete

Can you reverse the logic?

File.Copy (source, target, true) 

to overwrite the target then

File.Delete(source)

File.Delete Access to the path is denied

Try using the Microsoft.VisualBasic.FileIO.FileSystem methods as it has a handy DeleteDirectory method, I had access troubles awhile ago and this was the fix for my problem.

var directory = new DirectoryInfo(targetDir);
if (directory.Exists)
{
Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(targetDir, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
}

Does .NET File.Move copy and then delete

I could be wrong, but it seems that you do get delete-after-copy semantics.

MoveFile says that

To specify how to move the file, use the MoveFileEx or
MoveFileWithProgress function. To perform this operation as a
transacted operation, use the MoveFileTransacted function.

This implies that MoveFile does not provide either transaction semantics or guarantees as to "how the file is moved" (and there is nothing else in the documentation that refers to such).

MoveFileEx, on the other hand, states that

When moving a file, the destination can be on a different file system
or volume. If the destination is on another drive, you must set the
MOVEFILE_COPY_ALLOWED flag in dwFlags.

The effect of MOVEFILE_COPY_ALLOWED is

If the file is to be moved to a different volume, the function
simulates the move by using the CopyFile and DeleteFile functions. If
the file is successfully copied to a different volume and the original
file is unable to be deleted, the function succeeds leaving the source
file intact.

The way I interpret this is that since MoveFileEx does not give you the option of doing things otherwise when moving across volumes, it stands to reason that MoveFile also works in that mode as well.

In addition, moving across volumes means possibly moving across filesystems and even machines (especially when using UNC paths). In this situation there is no way to place the file in its destination path other than incrementally copying its contents, which seems to pretty much guarantee that the operation will be a delete-after-copy.



Related Topics



Leave a reply



Submit