代码审查:在给定完整文件路径的情况下确定文件夹是否存在?

发布于 2024-08-12 10:07:14 字数 500 浏览 4 评论 0原文

通过向函数传递文件的完整路径(例如 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

With a function being passed a full path to a file, such as C:\someFolder\anotherFolder\someXML.xml, determine whether the folder exists. Is there a smarter/better/more elegant way of doing this? Here is my implementation:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撩起发的微风 2024-08-19 10:07:14

只需使用 File.Exists 即可,接受完整路径。

编辑:抱歉,调用您的目录变量 f 让我感到困惑......我相信您可以翻译以下 C# 代码:-

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

.NET BCL ARM 对这些东西有相当多的报道,尽管我确信那里有更好的参考。 System.IO.PathEnvironment 文档可能就可以了。

just use File.Exists instead, it accepts a full path.

EDIT: Sorry, calling your directory variable f confused me.... I trust you can translate the following C# code:-

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

The .NET BCL ARM has decent coverage of this stuff, though I'm sure there's a better reference out there. The System.IO.Path and Environment docs would probably be just fine.

枯寂 2024-08-19 10:07:14

您可以使用 [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

You can use [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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文