代码审查:在给定完整文件路径的情况下确定文件夹是否存在?
通过向函数传递文件的完整路径(例如 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用 File.Exists 即可,接受完整路径。
编辑:抱歉,调用您的目录变量
f
让我感到困惑......我相信您可以翻译以下 C# 代码:-.NET BCL ARM 对这些东西有相当多的报道,尽管我确信那里有更好的参考。
System.IO.Path
和Environment
文档可能就可以了。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:-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
andEnvironment
docs would probably be just fine.您可以使用 [
File.Exists
](http://msdn.microsoft.com/en-us/library/system.io.file.exists(VS.71).aspx))You can use [
File.Exists
](http://msdn.microsoft.com/en-us/library/system.io.file.exists(VS.71).aspx))