2011-10-23 32 views
0

我正在製作音樂播放器應用程序。我正在使用ListBox來顯示歌曲。當用戶添加歌曲時,它會顯示歌曲的完整路徑。但我希望它只顯示歌曲名稱(歌曲可以位於任何驅動器的任何文件夾中)。 Windows媒體播放器控件正在播放歌曲。提前致謝!在列表框中存儲文件的路徑

+0

您需要說明您使用的是哪個演示文稿框架Sadia。這聽起來像它可能是WPF/Silverlight,但它可能是Winforms或其他。此外,您需要粘貼一些代碼以便人們更輕鬆地幫助。 – Stimul8d

+0

它是vb還是vba? – Tipx

回答

0

所以你只想從歌曲的整個路徑中提取歌曲名稱。一個簡單的棘手的邏輯將做到這一點。這是VBA

sub song_name_extractor() 
    song_path = "c:\songs\favret\mylove.mp3" ' Assume this is where the song is 
    song_name = Right(song_path, Len(song_path) - InStrRev(song_path, "\")) 
    Msgbox song_name 'outputs mylove.mp3 
    song_name = Left(song_name, InStrRev(song_name, ".") - 1) 
    Msgbox song_name ' outputs only mylove removes extensions of file 
end sub 

釋:

Right Func, cuts the right part of the string into sub-string of given number 
Len Func, To find the length of the string 
InStrRev Fun, gives the point of occurrence, of the given character in a string 
searching from right to left 
Left Func, cuts the Left part of the string into sub-string of given number 
0

我會做這樣的事情:
1.創建一個對象,它可以容納的歌曲信息。
2.創建一個列表,保存播放列表中的所有歌曲。
3.將該列表作爲數據源添加到列表框中,通過設置.DisplayMember,您將告訴wich屬性在列表框中將顯示爲listitemtext。
4.當listindex更改時,獲取存儲在listbox.SelectedItem中的對象,並將其輸入到一個songobject以使用它。

Public Class Form1 

Structure SongObject 
    Public SongPath As String 
    Public NameNoExtension As String 
    Public SongLength As Integer 
    Public SongRating As Integer 
    Private _FileName 
    Public Property FileName() As String 
     Get 
      Return _filename 
     End Get 
     Set(ByVal value As String) 
      _FileName = value 
     End Set 
    End Property 

    Public Sub New(ByVal path As String) 
     SongPath = path 
     FileName = IO.Path.GetFileName(path) 
     NameNoExtension = IO.Path.GetFileNameWithoutExtension(path) 
     SongLength = 0 'fix 
     SongRating = 5 'fix 
    End Sub 

End Structure 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Dim musicpath As String = "C:\Users\Public\Music\Sample Music\" 

    'Load songs into listbox 
    ListBox1.DisplayMember = "FileName" 
    Dim songs As New List(Of SongObject) 
    For Each f As String In IO.Directory.GetFiles(musicpath, "*.mp3") 
     songs.Add(New SongObject(f)) 
    Next 
    ListBox1.DataSource = songs 
End Sub 

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged 
    'Get songitem 
    Dim SelectedSong As SongObject = CType(ListBox1.SelectedItem, SongObject) 
    MsgBox("Path:" & SelectedSong.SongPath & vbCrLf & "FileName:" & SelectedSong.FileName) 
    'Todo: play selected song... 
End Sub 
End Class 

使用IO.Path.GetFileName(路徑)和IO.Path.GetFileNameWithoutExtension(路徑)來獲取文件名,而不是左/右/ INSTR /中和等。