vb.net 如何获取从 Visual Basic 2013 中的 OpenFileDialog 打开的文件的文件夹路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29314153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get folder path of file opened from OpenFileDialog in Visual Basic 2013
提问by Dr. Atul Tiwari
I am opening a file using OpenFileDialog. My code is as follows -
我正在使用OpenFileDialog. 我的代码如下 -
Public Sub ShowOpenDialog()
Dim f As New OpenFileDialog
f.InitialDirectory = GetFolderPath(SpecialFolder.MyDocuments)
f.Title = "Open File"
f.CheckFileExists = True
f.CheckPathExists = True
f.DefaultExt = "*.txt"
f.Filter = "Text (*.txt)|*.txt|All Files|*.*"
f.FilterIndex = 1
f.RestoreDirectory = True
If f.ShowDialog() = DialogResult.OK Then
'f.FileName displays file path, what I need is its folder path
'Performing action with f.FileName
End If
End Sub
I also need file's location (folder path), but I couldn't find, how to get it?
我还需要文件的位置(文件夹路径),但找不到,如何获取?
p.s. - I (also) need to open the file, so I have to use OpenFileDialoginstead of FolderBrowserDialog. That's why, I am searching for a way to get file's Folder Path from OpenFileDialog
PS -我(也)需要打开文件,所以我必须使用OpenFileDialog替代FolderBrowserDialog。这就是为什么,我正在寻找一种方法来获取文件的文件夹路径OpenFileDialog
回答by David
This returns the parent folder name. (Works for Files and Folders (Folders, which do not end with "\"))
这将返回父文件夹名称。(适用于文件和文件夹(文件夹,不以“\”结尾))
''Be sure to Import Imports System.IO
Function GetDirPath(ByVal file As String) As String
Dim fi As New FileInfo(file)
Return fi.Directory.ToString
End Function

