Search code examples
c#fileuwpmediaelement

How to open a media file in the specified directory without adding the file to the project


I want to open a file on a computer on a local network with its full directory. Something like that:

var path = "C:/User/Folder/video.mp4";
var stream = ...;
\\code
mediaElement.SetSource(stream,""); 

I haven't found any ways on the internet. There were options only to add a file to the project, but this is not what I need.


Solution

  • How to open a media file in the specified directory without adding the file to the project

    There are two ways to do it. FileOpenPicker and broadFileSystemAccess

    FileOpenPicker

    The first one is to use FileOpenPicker. When you use it, it will show a window that lets the user choose and open files. It does not require any extra permissions but users need to know where the file is and pick the file by themself.

    Code:

            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
            openPicker.FileTypeFilter.Add("*");
    
            StorageFile file = await openPicker.PickSingleFileAsync();
    
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.Source = MediaSource.CreateFromStorageFile(file);
            mediaPlayer.Play();
    

    broadFileSystemAccess

    The second one is to use the restricted capability called broadFileSystemAccess. You need to add the capability into your app's manifestfile like this:

        <Package
    ...
    xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
      IgnorableNamespaces="uap mp rescap">
    ...
    <Capabilities>
        <rescap:Capability Name="broadFileSystemAccess" />
    </Capabilities>
    

    Then you could use APIs from Windows.Storage Namespace to get files directly via path. Like:

     StorageFile file = await StorageFile.GetFileFromPathAsync("C:\\Users\\Administrator\\Desktop\\video.mp4");
    
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.Source = MediaSource.CreateFromStorageFile(file);
            mediaPlayer.Play();
    

    When you use this capability, please make sure that user has enabled the file system privacy setting after installed the app. You could find the settings in Settings > Privacy > File system.

    enter image description here