.NET Maui FileStream

Fritz Switzer 281 Reputation points
2022-08-28T21:00:03.69+00:00

I'm converting an UWP app to a .NET Maui, but having an issue with FileStream. Here is my working code in the UWP app:

string binaryFile="Resources\Images\alpha.jpg"

 private async static Task<Stream> GetBinaryStream(string binaryFile)  
        {  
            var storageFile = await Package.Current.InstalledLocation.GetFileAsync(binaryFile);  
            var storageStream = await storageFile.OpenSequentialReadAsync();  
            return storageStream.AsStreamForRead();  
        }  

I've tried multiple implementations, but I can't find an alternative to the line:

var storageStream = await storageFile.OpenSequentialReadAsync();

How do I replicate the UWP code to work with Maui?

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,489 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 42,431 Reputation points Microsoft Vendor
    2022-08-29T03:03:03.277+00:00

    Hello,

    You need to use File system helpers in MAUI to get the Stream from files on Windows platform.

    Referring to this documentation, you could find the following content:

    FileSystem.OpenAppPackageFileAsync
    Files that were added to the project with the Build Action of MauiAsset can be opened with this method. .NET MAUI projects will process any file in the Resources\Raw folder as a MauiAsset.

    Therefore, you need to add <MauiAsset Include="Resources\Images\**"/> in your project file at first, then you could use the following code to get Stream:

       // binaryFile = "Resources\\Images\\dotnet_bot.svg"  
       private async static Task<Stream> GetBinaryStream(string binaryFile)  
       {  
           // Read the source file  
           using Stream fileStream = await FileSystem.Current.OpenAppPackageFileAsync(binaryFile);  
           return fileStream;  
       }  
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.