Skip to content

File.Copy no longer respects FileShare.None on Linux/Mac in 5.0 #31429

@nguerrera

Description

@nguerrera

Found this taking a new runtime into dotnet/sdk test run environment, as one of our tests started failing on Linux/Mac.

Program.cs

using System;
using System.IO;

class Program
{
    static void Main()
    { 
        File.WriteAllText("x", "x");
        File.WriteAllText("y", "y");

        using (var stream = new FileStream("y", FileMode.Open, FileAccess.Read, FileShare.None))
        {
            File.Copy("x", "y", overwrite: true);
        }
        
        Console.WriteLine("Success");
    }
}

Repro.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp3.0;netcoreapp5.0</TargetFrameworks>
  </PropertyGroup>
</Project>

Repro steps

  • dotnet run -f netcoreapp3.0
  • dotnet run -f netcoreapp5.0

Expected result

Both 3.0 and 5.0 fail with IOExceptions

Actual result

Only 3.0 fails, 5.0 succeeds unexpectedly

3.0 (fails as expected)

Unhandled exception. System.IO.IOException: The process cannot access the file '/home/nicholg/src/sdk/q/y' because it is being used by another process.
   at System.IO.FileStream.Init(FileMode mode, FileShare share, String originalPath)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)      
   at System.IO.FileSystem.CopyFile(String sourceFullPath, String destFullPath, Boolean overwrite)
   at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
   at Program.Main()

5.0 (succeeds unexpectedly)

Success

@stephentoub @JeremyKuhne

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions