【发布时间】:2018-11-21 01:11:42
【问题描述】:
对于我的应用程序,我允许用户重命名项目,这意味着我需要重命名磁盘上的目录和文件。问题是,如果目录是由用户打开的。我会收到错误“对路径'...'的访问被拒绝。”,但此时我已经重命名了几个文件。
我的问题是,在我开始进行更改之前,是否有办法验证目录或文件是否可以重命名而没有任何问题。
这是我目前拥有的代码的 sn-p:
Try
Dim directory As New IO.DirectoryInfo(WorkingDirectory)
' Verify if the old directory path exists on the disk, if so rename it using the new directory name.
If IO.Directory.Exists(oldDirectoryPath) Then
' Delete old project file
If IO.File.Exists(oldFilePath) Then
IO.File.Delete(oldFilePath)
End If
' Rename all files in subdirec with new name
If IO.Directory.Exists(oldSubDirectory) Then
For Each file As String In IO.Directory.GetFiles(oldSubDirectory,
$"*_{oldName}.*",
IO.SearchOption.AllDirectories)
FileIO.FileSystem.RenameFile(file, newFileName)
Next
End If
FileIO.FileSystem.RenameDirectory(oldDirectoryPath, directory.Name)
End If
Catch ex As IO.IOException
' Show error message to user
End Try
【问题讨论】:
-
为什么不直接使用
try/catch? -
你必须使用 try/catch。验证和更改之间的时间,其他进程可以删除访问权限。仅在 RenameFile 上放置一个 try/catch,但有适当的例外。当您检查文件夹是否存在并尝试重命名时,您的文件夹甚至可能已被删除。
-
我确实有一个 try/catch 方法,但是如果重命名几个文件后出现错误,那么我就卡在中间了。
-
在 Catch 中添加回滚。 If newName Then oldName.