【问题标题】:Code review: Determining whether a folder exists, given the full file path?代码审查:在给定完整文件路径的情况下确定文件夹是否存在?
【发布时间】:2023-03-30 02:00:02
【问题描述】:

通过向函数传递文件的完整路径(例如C:\someFolder\anotherFolder\someXML.xml),确定文件夹是否存在。有没有更聪明/更好/更优雅的方式来做到这一点?这是我的实现:

Private Function FolderExists(ByVal fullPath As String) As Boolean
    Dim folders() As String = fullPath.Split("\")
    Dim folderPath As String = ""
    For i As Integer = 0 To folders.Length - 2 'subtract 2 to avoid appending the filename.
        folderPath += folders(i) + "\"
    Next
    Dim f As New DirectoryInfo(folderPath)
    Return f.Exists
End Function

【问题讨论】:

    标签: .net vb.net path-manipulation


    【解决方案1】:

    只需改用File.Exists,它接受完整路径。

    编辑:对不起,调用你的目录变量f 让我很困惑......我相信你可以翻译以下 C# 代码:-

     return Directory.Exists( Path.GetDirectoryName( fullPath ) );
    

    .NET BCL ARM 对这些东西有不错的报道,尽管我确信那里有更好的参考。 System.IO.PathEnvironment 文档可能会很好。

    【讨论】:

    • 我应该知道会为此内置一个 API 调用 :) 谢谢!
    • 要翻译 C# 代码,只需删除分号。 C# 太罗嗦了 :)
    【解决方案2】:

    您可以使用 [File.Exists](http://msdn.microsoft.com/en-us/library/system.io.file.exists(VS.71).aspx))

    Private Function FolderExists(ByVal fullPath As String) As Boolean
      return (File.exists(fullPath)
              And (File.GetAttributes(fullPath) And FileAttributes.Directory))
    End Function
    

    【讨论】:

    • -1:他有一个包含文件名的完整路径,需要对其进行拆分以确定 目录 是否存在,并且正在寻找一种巧妙的方法来做到这一点
    猜你喜欢
    • 2013-01-29
    • 2011-09-06
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 2015-05-09
    相关资源
    最近更新 更多