MAUI - Opening and reading lines from a Text File

Riffy 276 Reputation points
2022-11-02T22:17:31.577+00:00

Hi

I am migrating my projects from Xamarin to Net MAUI and have an issue with giving a pathname, opening and reading a Text files which are declared as MauiAsset.

Example of one file declared in .csproj

   <ItemGroup>  
     <MauiAsset Include="Resources\Assets\Text File 1.txt" />  
   </ItemGroup>  

As the method for opening/reading text files (a line at a time) is different in MAUI, I am having trouble coding these.

I have attempted the following:

   public void ReadData()  
           {  
         
               DataFile = "Text File 1.txt";  
               // is this correct Call?   
               Task<string> task = ReadLines();  
           }  
         
         
         
           public async Task ReadLines(string DataFile)  
           {  
               // Open the source file  
               using Stream fileStream = await FileSystem.Current.OpenAppPackageFileAsync(DataFile);  
               using StreamReader sr = new(fileStream);  
               // Position to start line   
               for (int i = 1; i < StartLine; i++)  
               {  
                   sr.ReadLine();  
               }  
         
               // Read from  start line to End line  
               for (int i = StartLine; i < EndLine; i++)  
               {  
                   DataText = sr.ReadLine();  
                   if (DataText != "" && DataText != null)  
                   {  
                       ItemDets.Add(new ItemDets { DetDesc = DataText, DetId = "" });  
                   }  
               }  
           }  

I am difficulty setting fileStream to correct path for DataFile . I need the correct alternates for FileSystem.Current.OpenAppPackageFileAsync for my text file locations above and reading the files.

Have searched online for solution on setting this but can't find anything relevant for MAUI.

Any help would be appreciated.

Thanks

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

Accepted answer
  1. Arun Siripuram 801 Reputation points
    2022-11-04T14:34:37.297+00:00

    @Riffy

    Problem Statement: Unable to open and read Text files which are declared as MauiAsset with Net MAUI project.

    Solution: NET MAUI project enables resource files to be stored in a single location while being consumed on each platform. This includes fonts, images, the app icon, the splash screen, raw assets, and CSS files for styling .NET MAUI apps. Each image resource file is used as a source image, from which images of the required resolutions are generated for each platform at build time. Resource files should typically be placed in the Resources folder of your .NET MAUI app project, or child folders of the Resources folder, and must have their build action set correctly. The following table shows the build actions for each resource file type:

    257283-image.png

    Please move the file from Assets folder to "Resources\Raw" folder. It worked for me. for more information, please feel free to refer https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/single-project

    public void ReadData()
    {
    string path = FileSystem.AppDataDirectory;
    DataFile = @"Text File 1.txt";
    Task<string> task = ReadLines(DataFile);
    Console.WriteLine(task.Result);
    }
    public async Task<string> ReadLines(string DataFile)
    {
    string AllOfTexts = "";
    try
    {
    // Open the source file
    using Stream fileStream = await FileSystem.Current.OpenAppPackageFileAsync(DataFile);
    using StreamReader sr = new(fileStream);

            string line;  
              
            while ((line = sr.ReadLine()) != null)  
            {  
                Console.WriteLine(line);  
                AllOfTexts += line;  
                ItemDets.Add(new TextData { Desc = line });  
            }  
            return AllOfTexts;  
        }  
        catch (Exception ex)  
        { Console.WriteLine(ex.Message); }  
        return AllOfTexts;  
    }  
    

    internal class TextData
    {
    public string Desc { get; set; }
    }

    Please "Accept the answer" if this information helped you. This will help us and others in the community as well.


1 additional answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 71,836 Reputation points Microsoft Vendor
    2022-11-03T03:11:16.747+00:00

    Hello,

    As the method for opening/reading text files (a line at a time) is different in MAUI, I am having trouble coding these.

    You don’t need to get the startline, then get text file line by line. You can judge the result of sr.ReadLine()). If result is empty. This is the end of the text file. If not, we can read it continuously.

    And I notice you want to return the string of ReadLines method, So I returned of all texts in the TXT files, you can refer to the following code.

       string DataFile;  
           public async void ReadData()  
           {  
         
              DataFile = "Text File 1.txt";  
               // is this correct Call?  
               string task = await ReadLines(DataFile);  
           }  
         
         
           List<ItemDets> ItemDets = new List<ItemDets>();  
           public async Task<string> ReadLines(string DataFile)  
           {  
               // Open the source file  
               using Stream fileStream = await FileSystem.Current.OpenAppPackageFileAsync(DataFile);  
               using StreamReader sr = new(fileStream);  
                 
         
              string line;  
               string AllOfTexts="";  
               while ((line = sr.ReadLine()) != null)  
               {  
                   Console.WriteLine(line);  
                   AllOfTexts += line;  
                   ItemDets.Add(new ItemDets { DetDesc = line, DetId = "" });  
               }  
               return AllOfTexts;     
          }  
    

    Best Regards,

    Leon Lu


    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.