macOS下检测Windows共享驱动器文件存在性问题
问题原因
MacOS下的.NET运行时(包括Visual Studio for Mac使用的环境)不支持Windows的UNC路径格式(\\servername\folder\file.pdf),会将这种路径识别为相对路径,因此解析时会拼接到当前项目目录下,导致FileInfo.Exists返回false。而Windows系统原生支持UNC路径,所以相同代码能正常返回true。
解决方法
方法1:使用Mac挂载后的本地映射路径
既然你已经挂载了Windows共享驱动器,Mac会将其挂载到/Volumes目录下。比如共享目录名为folder,对应的本地路径是/Volumes/folder/file.pdf,直接替换原代码中的UNC路径即可:
FileInfo fileInfo = new FileInfo(@"/Volumes/folder/file.pdf"); bool exists = fileInfo.Exists;
你可以在Mac访达中找到挂载的驱动器,右键选择「显示简介」查看具体挂载路径。
方法2:通过SMB协议路径访问
将Windows UNC路径转换为Mac支持的SMB协议路径,再转换为本地可识别路径:
// 转换为SMB格式路径 string smbPath = @"\\servername\folder\file.pdf".Replace(@"\\", "smb://").Replace(@"\", "/"); // 转换为Mac本地路径 string localPath = new Uri(smbPath).LocalPath; FileInfo fileInfo = new FileInfo(localPath); bool exists = fileInfo.Exists;
方法3:跨平台路径适配(推荐)
如果代码需要同时在Windows和Mac运行,可通过判断操作系统动态转换路径:
string windowsUNCPath = @"\\servername\folder\file.pdf"; string targetPath; if (OperatingSystem.IsWindows()) { targetPath = windowsUNCPath; } else if (OperatingSystem.IsMacOS()) { string smbPath = windowsUNCPath.Replace(@"\\", "smb://").Replace(@"\", "/"); targetPath = new Uri(smbPath).LocalPath; } else { // 其他系统的 fallback 逻辑 targetPath = windowsUNCPath; } FileInfo fileInfo = new FileInfo(targetPath); bool exists = fileInfo.Exists;
内容的提问来源于stack exchange,提问作者dmvn denso
相关产品推荐
相关产品推荐

