You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

复制文件至网络共享后偶现“文件正被其他进程占用”异常

网络共享文件复制后读取出现进程占用异常问题

我们的应用包含ASP.NET Web服务器与处理各类任务的API服务器。在特定工作流中,用户上传文件后,Web服务器将其复制到网络共享目录供Job服务器读取,Job服务器通过扫描MSSQL表新增行获取通知。今年集成测试时,该流程随机出现以下异常:
System.IO.IOException: The process cannot access the file '\\a\\b\\c.xlsx' because it is being used by another process.

本地开发与测试环境无此问题,但将共享目录从本地文件系统移至网络共享后,异常开始出现。通过以下C#代码可随机复现问题:

static void Main(string[] args)
{
    const string DestinationDirectory = @"\\10.122.xxx.xxx\Testing";

    var inputPath = args[0];
    var filename = Path.GetFileName(inputPath);
    var destinationPath = Path.Combine(DestinationDirectory, filename);

    Console.WriteLine(filename);

    Console.WriteLine("Copying the source file...");
    File.Copy(inputPath, destinationPath, true);

    Console.WriteLine("Opening the destination file...");
    try
    {
        using var _ = File.Open(destinationPath, FileMode.Open, FileAccess.Read);
        Console.WriteLine("Success!");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}

使用以下批处理脚本运行时,约每10次出现1次异常:

@echo off

for /l %%x in (1, 1, 10) do (
    FileShareDemo.exe "C:\a\b\c\myfile"
)

异常堆栈信息:

myfile
Copying the source file...
Opening the destination file...
System.IO.IOException: The process cannot access the file '\\10.122.xxx.xxx\Testing\myfile' because it is being used by another process.
   at Microsoft.Win32.SafeHandles.SafeFileHandle.CreateFile(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options)
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize, Nullable`1 unixCreateMode)
   at System.IO.Strategies.OSFileStreamStrategy..ctor(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize, Nullable`1 unixCreateMode)
   at System.IO.Strategies.FileStreamHelpers.ChooseStrategyCore(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize, Nullable`1 unixCreateMode)
   at System.IO.File.Open(String path, FileMode mode, FileAccess access)
   at FileShareDemo.Program.Main(String[] args)
  • 测试发现文件会被短暂锁定,导致异常随机出现
  • 该问题在.NET 6与.NET 8中均存在
  • 曾怀疑是Windows系统问题,但使用以下批处理脚本执行相同操作未触发异常,因此认为是.NET相关问题:
@echo off

set file=myfile
set source="C:\a\b\c\%file%"
set destination="\\10.122.xxx.xxx\Testing\%file%"

for /l %%x in (1, 1, 10) do (
    echo Copying...
    copy %source% %destination%
    
    echo Reading...
    type %destination%
    REM powershell -command "Get-Content %destination% -Encoding byte -TotalCount 2"
)

尝试使用微软Handle工具查找文件句柄,但工具响应过慢无法捕获。

内容的提问来源于stack exchange,提问作者Rob P.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 13:33:38