如何在图片框中显示文件夹中的随机照片并打印出不带扩展名的照片名称

How to display a random photo from a folder in a picture box and print out the photo name without extension

我有一个名为 "MyPhotos" 的文件夹,我想在每次单击 "Myphoto" 中的命令按钮时显示一张随机照片,并以不带格式的形式打印出所显示照片的名称延期 。我正在尝试以下代码,但仍然无法获取照片名称

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
    Dim DirectoryPath As String = Application.ExecutablePath
    Directorypath = DirectoryPath.Substring(0, Directorypath.LastIndexOf("\bin")) & "\MyPhotos"
    Dim bm As New Bitmap(GetRandomImageFilePath(Directorypath))
    picImage.Image = bm
End Sub

Public Function GetRandomImageFilePath(ByVal folderPath As String) As String
    Dim files() As String = Directory.GetFiles(folderPath, "*.jpg")
    Dim random As Random = New Random()
    Return files(random.Next(0, files.Length))
End Function

有什么帮助吗?

您已经拥有 GetRandomImageFilePath 返回的完整路径。 如果您只想要文件名,请在调用 Sub

中执行此操作
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
    Dim DirectoryPath As String = Application.ExecutablePath
    Directorypath = DirectoryPath.Substring(0, Directorypath.LastIndexOf("\bin")) & "\MyPhotos"
    Dim imagePath as String = GetRandomImageFilePath(Directorypath)
    Dim fileInfo as New FileInfo(imagePath)
    Dim imageName as String = fileInfo.Name
    Dim bm As New Bitmap(imagePath)
    picImage.Image = bm
End Sub

我将此添加到您的按钮方法中。我只使用 FileInfo 来获取详细信息。

    Dim finfo As FileInfo = New FileInfo(GetRandomImageFilePath(DirectoryPath))

    Dim filename As String = finfo.Name.Replace(finfo.Extension, "")
    Dim bm As New Bitmap(finfo.FullName)
    picImage.Image = bm