Tania Akter Tania Akter - 3 months ago 20
C# Question

Why isn't the media source Safefilename?

Xaml:

<MediaElement x:Name="mePlayer" Margin="64,0,90,61" ></MediaElement>
<ListBox x:Name="listbox4" Background="Salmon" BorderBrush="Black" BorderThickness="3" >
</ListBox>


Cs:

private void load_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.DefaultExt = ".mp3";
ofd.Filter = "All|*.*";
ofd.Multiselect = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{
for (int i = 0; i < ofd.FileNames.Length; i++)
{
listbox4.Items.Add(ofd.FileNames[i].ToString());
listbox4.SelectedItem = ofd.FileName;
mePlayer.Source = new Uri(listbox4.SelectedItem.ToString(), UriKind.RelativeOrAbsolute);
mePlayer.LoadedBehavior = MediaState.Play;
}
}
}


Note:

It's working smoothly but when when I replace FileNames To SafeFileNames for hiding item location.

Then it's not working for here.

Please help me.

I want to add items on listbox filename without path.

How possible?

Like This

Answer

This code should work for you. Please read the comments in the code before you proceed.

     private Dictionary<string, string> fileDictionary = new Dictionary<string, string>(); 

    private void load_Click(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
        ofd.DefaultExt = ".mp3";
        ofd.Filter = "All|*.*";
        ofd.Multiselect = true;
        Nullable<bool> result = ofd.ShowDialog();
        if (result == true)
        {

            for (int i = 0; i < ofd.FileNames.Length; i++)
            {
                var filePath = ofd.FileNames[i];
                var fileName = System.IO.Path.GetFileName(filePath);
                fileDictionary.Add(fileName, filePath);
                // not sure about this logic. You may need to reconsider what you are trying to do here.
                //Instead of doing this, create a click event for the list box and get the selected file path to be played from the dictionary.
                listbox4.Items.Add(fileName);                  
            }
        }
    }

 private void listbox4_SelectionChanged(object sender, SelectionChangedEventArgs e) 
 { 
    if (listbox4.SelectedItem != null) 
    { 
        var selectedFile = listbox4.SelectedItem.ToString();
        string selectedFilePath;
        fileDictionary.TryGetValue(selectedFile, out selectedFilePath);
        if (!string.IsNullOrEmpty(selectedFilePath))
        {
            mePlayer.Source = new Uri(selectedFilePath, UriKind.RelativeOrAbsolute);
            mePlayer.LoadedBehavior = MediaState.Play;
        }
    } 
 }