首页 > 解决方案 > 验证是否允许重命名目录和文件

问题描述

对于我的应用程序,我允许用户重命名项目,这意味着我需要重命名磁盘上的目录和文件。问题是,如果目录是由用户打开的。我会收到错误“拒绝访问路径'...'。 ”,但此时我已经重命名了几个文件。

我的问题是,在我开始进行更改之前,是否有办法验证目录或文件是否可以重命名而没有任何问题。

这是我到目前为止的代码片段:

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

标签: .netwpfvb.netprism

解决方案


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


推荐阅读