vb.net 在不打开文件的情况下获取文件名和路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18770678/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:03:20  来源:igfitidea点击:

Get file name and path without opening file

vb.netfilepathdirectory

提问by Bob Ma

I am studying Visual Basic .NET.

我正在学习 Visual Basic .NET。

And, I am trying to find way to get file name and directory path.

而且,我试图找到获取文件名和目录路径的方法。

For example, When I click button , then we can search file by openfile dialog.

例如,当我单击按钮时,我们可以通过打开文件对话框搜索文件。

When We select the file then we will get path and file name such as "C:\data\picture\my_pic.jpg".

当我们选择文件时,我们将得到路径和文件名,例如“C:\data\picture\my_pic.jpg”。

However, program does not open file. It just return the string type path for file.

但是,程序不会打开文件。它只返回文件的字符串类型路径。

I am not really sure how to get path.

我不太确定如何获得路径。

Does anyone know how to get path ?

有谁知道如何获得路径?

Thanks

谢谢

回答by J...

If all you need is the path, and I'm assuming you're using Winforms, then :

如果您只需要路径,并且我假设您使用的是 Winforms,那么:

Using ofd As New OpenFileDialog
    If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
        MsgBox(ofd.FileName)
    End If
End Using

An OpenFileDialogdoesn't actually open the file - it returns the path (or paths) to the selected files via the .FileName(or .FileNamesfor multiple files) property, and your application then can use them in whatever way it wants - either opening the file or doing something else to it, etc.

AnOpenFileDialog实际上并没有打开文件 - 它通过.FileName(或.FileNames对于多个文件)属性返回所选文件的路径(或路径),然后您的应用程序可以以任何它想要的方式使用它们 - 打开文件或执行别的东西,等等。

回答by Nicholas Post

There is no default 'do this when file is selected' event within the OpenFileDialog. All it does is allows a user to select a file, and then you determine what to do with it.

OpenFileDialog 中没有默认的“选择文件时执行此操作”事件。它所做的只是允许用户选择一个文件,然后您决定如何处理它。

The OpenFileDialog class has an event called FileOK, which gets fired after a user selects a file and clicks the 'OK' button. If you create a sub that Handles OpenFileDialog.FileOK, you can then access the OpenFileDialog.FileName.

OpenFileDialog 类有一个名为 的事件FileOK,在用户选择文件并单击“确定”按钮后会触发该事件。如果您创建了一个子文件Handles OpenFileDialog.FileOK,那么您就可以访问OpenFileDialog.FileName.

The FileNamewill return the full path to the file. Once you have this, it is up to you to determine what to do with the file. If you want to display the image in your program, perhaps create a PictureBoxand load the image in it. If you want to load it in an external program, use Process.Start()and pass the file path as a parameter to it.

FileName将返回文件的完整路径。获得此文件后,由您决定如何处理该文件。如果你想在你的程序中显示图像,也许可以创建一个PictureBox并在其中加载图像。如果要在外部程序中加载它,请使用Process.Start()文件路径并将其作为参数传递给它。