Skip to content

File.Move (overwrite) unreliable because FileShare.Delete access of target file ignored #114230

Open

Description

@StefanBertels

Description

I detected a problem with File.Move which occurs more frequently if more antivirus scanning work is done (probably Defender ATP). IMO this is a bug in MoveFileEx win32api method but there doesn't seem to be a viable issue tracker for that and the failing example code is .NET anyway.

Environment is Windows 11 (24H2), local hard drive (SSD), .NET 8 => nothing special.

When narrowing down errors I finally built a loop reproducing it:

for(int i = 0; i < 100000; ++i)
{
  System.IO.File.WriteAllText(sourceFilePath, "test");
  System.IO.File.Move(sourceFilePath, destFilePath, true);
}

If you run this code then destFilePath will be overwritten again and again.
On a non-corporate Windows 11 Pro machine with local filenames (e.g. Path.GetTempFilename()) and with standard defender this causes 0-2 errors in 100000 iterations.

Error message is "Access denied" and as far as I could see the target file is blocked (opened). My guess is that antivirus scanning of the written file is done AFTER the filestream is closed (WriteAllText method returns).

If you run this loop on a corporate machine with intensive scanning (defender ATP) there will be a failure more often. I saw failures every 50-100 iterations in average, sometimes on the first or second iteration.

My guess is the same as in this reddit: constant_file_locking
Sounds very plausible to me for my problem: file probably is opened by antivirus with ShareMode: Read, Delete.

When I add File.Delete(destFilePath) before File.Move everything works fine -- but atomicity of the operation is lost. Internmediate situation is: old destination file already dropped, new not created yet. Therefore File.Delete is no viable replacement.

My example unit test below shows that File.Delete(destination) is allowed if destination file is not opened or just opened using FileShare.Delete.
But calling File.Move(..., destination, overwrite: true) is not allowed (causing an exception).

File.Move (MoveFileEx) must preceed with overwrite: true when file can be deleted. This should be fixed in the API / filesystem.

If this isn't possible a workaround would be this: File.Move would wait for any antivirus scanning engine to finish instead of just returning an error. This sounds like a bad design decision but logical if the antivirus scanning isn't fully transparent (which would be the correct solution, but obviously causing slow downs).

Of course this problem can be offloaded to the developer (try/catch/retry) or the user but I think it is a logic bug (either in File.Move or in antivirus integration) that should be fixed.

Reproduction Steps

[Fact]
void FileMoveBug()
{
	var sourceFilePath = Path.GetTempFileName();
	var destFilePath = Path.GetTempFileName();
	
	var msSenseSimulation = new FileStream(destFilePath, new FileStreamOptions()
	{
		Options = FileOptions.None,
		Access = FileAccess.Read,
		Mode = FileMode.Open,
		Share = FileShare.Delete
	});
	
	// File.Delete(destFilePath); // this line fixes the code, but creates a small gap where destination file does not exist (not atomic anymore)
	System.IO.File.Move(sourceFilePath, destFilePath, true);

	msSenseSimulation.Dispose();
}

Expected behavior

If File.Delete works flawless then File.Move(overwrite:true) should, too.

Actual behavior

Unit test fails (see above).

In real world processes sometimes fail.
Failure frequency seems to depend on performance / amount of antivirus scanning.

Regression?

No response

Known Workarounds

a) File.Delete (other semantics)
b) try/catch/retry-loop everytime when calling File.Move with overwrite:true

Configuration

.NET 8
Windows 11 (Pro / Enterprise)
x64
local filesystem

Other information

Related:

https://www.reddit.com/r/sysadmin/comments/xm5qow/comment/jamvwaa/?utm_source=share&utm_medium=web2x&context=3

Activity

  1. added
    untriaged
    on Apr 3, 2025
  2. dotnet-policy-service commented on Apr 3, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-io
    See info in area-owners.md if you want to be subscribed.

  3. KalleOlaviNiemitalo commented on Apr 4, 2025

    @KalleOlaviNiemitalo

    I hypothesized that perhaps DeleteFile breaks opportunistic locks (oplocks) and MoveFileEx(MOVEFILE_REPLACE_EXISTING) doesn't. But no, that breaks oplocks too, according to [MS-FSA] §2.1.5.15.11 FileRenameInformation; and it is implemented in FASTFAT, presumably then in NTFS and ReFS as well.

  4. JochenHuck commented on Jun 23, 2025

    @JochenHuck

    I can reproduce the described issue on my machine (Windows 11 Enterprise 10.0.26100, .NET 8.0.411) every ~150th iteration. Process Monitor reveals that mssense.exe heavily accesses the destination file. The described workaround of deleting the file prior to the move works.

  5. removed
    untriaged
    on Jul 23, 2025
  6. added this to the Future milestone on Jul 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions