【问题标题】:Set the path from an OpenFileDialog to a variable设置从 OpenFileDialog 到变量的路径
【发布时间】:2023-03-23 12:44:01
【问题描述】:

我有以下代码将文件名从 OpenFileDialog 设置为变量:

Dim OpenDLG As New OpenFileDialog
File = OpenDLG.FileName.ToString()
Dim xPath As String = File
        Dim ArrPath() = xPath.Split("\")
        Dim wPathLong = ArrPath(ArrPath.Length - 1)

但现在我想为路径设置相同的内容。 So: when a file is selected and set the path (without the filename) to a variable.

我尝试修改现有代码,但无法完成。

如何修改代码,以便在选择文件并将路径(不带文件名)设置为变量时?

【问题讨论】:

    标签: .net vb.net file variables path


    【解决方案1】:

    您可以使用GetDirectoryName。示例代码:

    Dim OpenDLG As New OpenFileDialog
    OpenDLG.ShowDialog()
    Dim xPath As String = OpenDLG.FileName
    Dim wPathLong = System.IO.Path.GetDirectoryName(xPath) 'Bear in mind that it does not include an ending "\"
    

    【讨论】:

      【解决方案2】:

      与其自己解析路径,不如使用Path 类(在System.IO 命名空间中)中的方法会更好、更容易,例如:

      Dim filePath As String = OpenDLG.FileName
      Dim fileName As String = Path.GetFileName(filePath)
      Dim folderPath As String = Path.GetDirectoryName(filePath)
      

      【讨论】:

        猜你喜欢
        • 2011-11-21
        • 1970-01-01
        • 1970-01-01
        • 2017-06-02
        • 2014-02-08
        • 1970-01-01
        • 1970-01-01
        • 2010-10-01
        • 2023-03-02
        相关资源
        最近更新 更多