Search code examples
c#windowswindows-8.1store

What to Use to Pick Multiple files (Media files) and retrieve them in a StorageFile collection at custom/desired index?


I have a list in which i retrieve multiple mp3 files. Now when i want to add files again, i pick files from picker but they overwrite the previous files in IReadOnlyList filesList

i want that if i choose files again...then they should go to the next index of filesList

Ex: First time i pick 3 files and they go to filesList[0], filesList[1], filesList[2]. Now I again click on addmusicbtn to pick files and i pick 2 files. Now what i want is to get these files on filesList[3] and filesList[4]. But IReadOnlyList is'nt allowing to do this, it starts storing from index 0.

I've also tried IList but it does'nt work with File Picker

    IReadOnlyList<StorageFile> fileList;
    private async void addmusicbtn_Click(object sender, RoutedEventArgs e)
    {
            var fop = new FileOpenPicker();
            fop.FileTypeFilter.Add(".mp3");
            fop.FileTypeFilter.Add(".mp4");
            fop.FileTypeFilter.Add(".avi");
            fop.FileTypeFilter.Add(".wmv");
            fop.ViewMode = PickerViewMode.List;

            fileList = await fop.PickMultipleFilesAsync();

                foreach (StorageFile file in fileList)
                {
                    mlist.Items.Add(file.Name);
                    stream = await file.OpenAsync(FileAccessMode.Read);
                }
                mediafile.SetSource(stream, file.ContentType);
                mediafile.Play();
    }

Solution

  • PickMultipleFilesAsync will return the files picked during that instance. If you want to add them to a list of previously picked files then add them to a separate list similar to how you add them to mlist (but save the StorageFile not the path. The StorageFile is much more useful).

    Here's a modified version of your code which keeps a cumulative fileList:

    List<StorageFile> fileList; // don't forget to initialize this somewhere!
    private async void addmusicbtn_Click(object sender, RoutedEventArgs e)
    {
            var fop = new FileOpenPicker();
            fop.FileTypeFilter.Add(".mp3");
            fop.FileTypeFilter.Add(".mp4");
            fop.FileTypeFilter.Add(".avi");
            fop.FileTypeFilter.Add(".wmv");
            fop.ViewMode = PickerViewMode.List;
    
            IReadOnlyList<StorageFile> pickedFileList;
    
            pickedFileList= await fop.PickMultipleFilesAsync();
            // add the picked files to our existing list
            fileList.AddRange(pickedFileList);
    
            // I'm not sure if you want fileList or pickedFileList here:
            foreach (StorageFile file in fileList)
            {
                mlist.Items.Add(file.Name);
                stream = await file.OpenAsync(FileAccessMode.Read);
                mediafile.SetSource(stream, file.ContentType);
            }
            mediafile.Play();
    
    }