【问题标题】:Verify if directories and files are allowed to be renamed验证是否允许重命名目录和文件
【发布时间】: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.

标签: .net wpf vb.net prism


【解决方案1】:

抱歉,我无法发表评论。但我认为这是一个非常有趣的问题。 但我想知道如何先重命名目录,然后再重命名文件。如果该目录中的任何文件已打开,则您无法重命名该目录,因此您也没有重命名任何文件。只是一个想法!

【讨论】:

    猜你喜欢
    • 2013-12-05
    • 1970-01-01
    • 2015-02-05
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多