Mac主机Docker映射卷中.Net Core创建FileStream遇FileNotFoundException
问题:Docker跨平台卷映射下FileStream偶尔抛出FileNotFoundException
环境背景
- 应用运行在Linux Docker容器中,宿主系统为MacOS,处于调试模式
- Docker Compose卷映射配置:
volumes: - /Users/blabla/Temp:/temp
异常现象
调用File.OpenRead时偶尔抛出System.IO.FileNotFoundException,堆栈信息如下:
at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter) at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String path, OpenFlags flags, Int32 mode) at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize) at System.IO.Strategies.OSFileStreamStrategy..ctor(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize) at System.IO.Strategies.FileStreamHelpers.ChooseStrategy(FileStream fileStream, String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, Int64 preallocationSize) at System.IO.FileStream..ctor(String path, FileMode mode)
测试场景对比
场景1:使用Mac宿主映射卷中的文件
测试代码:
var mappedFolderPath = "/temp/testFile.png"; var exist = System.IO.File.Exists(mappedFolderPath); for (int i = 0; i < 1000; i++) { try { using var streamForTest = System.IO.File.OpenRead(mappedFolderPath); var justForTest = streamForTest.Length; } catch (Exception ex) { // 3-4次循环后触发异常 var exception = ex; } }
现象:File.Exists返回true,但循环几次后抛出上述异常。
场景2:使用容器内输出目录的文件
通过.csproj配置将文件复制到容器内输出目录:
... <ItemGroup> <None Update="StaticContent\testFile.png"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> ...
测试代码:
var root = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); var path = Path.Combine(root, "StaticContent", "testFile.png"); var exist = System.IO.File.Exists(path); for (int i = 0; i < 1000; i++) { try { using var streamForTest = System.IO.File.OpenRead(path); var justForTest = streamForTest.Length; } catch (Exception ex) { // 从未触发异常 var exception = ex; } }
现象:File.Exists返回true,循环全程无异常。
核心疑问
两种场景下File.Exists均返回true,为何映射卷场景会偶尔抛出文件不存在的异常?
内容的提问来源于stack exchange,提问作者Artem
相关产品推荐
相关产品推荐

