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

Why does media source not work with Safefilenames?

I want to add filenames (without the full path) to the

ListBox
.

Like This

The code below is working smoothly, but when when I change
FileNames
to
SafeFileNames
(for hiding item location) it's not working anymore.

XAML



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


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;
}
}
}

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;
        }
    } 
 }