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:
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.