VB.Net Core非Windows平台下FileSystem.Rename跨平台替代方案咨询
全平台替代方案
FileSystem.Rename 属于Microsoft.VisualBasic命名空间下的Windows专属API,所以会触发CA1416平台兼容警告,可使用.NET内置的全平台API直接替换,无需引入第三方依赖:
文件重命名:用
File.Move
原生支持全平台,用法和FileSystem.Rename基本一致,.NET Core 3.0及以上版本支持通过第三个参数控制是否覆盖已有目标文件:' 原写法 ' FileSystem.Rename("path/to/old.txt", "path/to/new.txt") ' 替换后写法 File.Move("path/to/old.txt", "path/to/new.txt", overwrite:=True)目录重命名:用
Directory.Move
目录重命名场景直接替换即可:' 原写法 ' FileSystem.Rename("path/to/oldDir", "path/to/newDir") ' 替换后写法 Directory.Move("path/to/oldDir", "path/to/newDir")兼容封装方案(少改现有代码)
如果项目中FileSystem.Rename调用量很大,可以自行封装兼容方法,全局替换调用入口即可保留原使用习惯:Imports System.IO Public Module FileSystemCompat ''' <summary> ''' 全平台兼容的重命名方法,兼容原FileSystem.Rename调用逻辑 ''' </summary> Public Sub Rename(sourcePath As String, destinationPath As String, Optional overwrite As Boolean = False) ' 处理文件重命名 If File.Exists(sourcePath) Then File.Move(sourcePath, destinationPath, overwrite) Exit Sub End If ' 处理目录重命名 If Directory.Exists(sourcePath) Then If Directory.Exists(destinationPath) AndAlso overwrite Then Directory.Delete(destinationPath, recursive:=True) End If Directory.Move(sourcePath, destinationPath) Exit Sub End If Throw New FileNotFoundException("待重命名的路径不存在", sourcePath) End Sub End Module
如果仅需要在Windows平台运行,不需要跨平台,可以在对应代码行上方加#Disable Warning CA1416临时屏蔽警告,不推荐跨平台场景使用该方法。
内容的提问来源于stack exchange,提问作者Reciter of Poetry
相关产品推荐
相关产品推荐

