Hello,
how can we create text file using maui and access it?
How to write a text file somewhere on emulator or device in public or app folder?
It is recommended to write/read a file in the app folder. You can use File system helpers to write/read text file.
Please check the following code to write text to a text file in the app folder.
public async void WirteTextToFile(string text, string targetFileName)
{
// Write the file content to the app data directory
string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, targetFileName);
using FileStream outputStream = System.IO.File.OpenWrite(targetFile);
using StreamWriter streamWriter = new StreamWriter(outputStream);
await streamWriter.WriteAsync(text);
}
Please check the following code to read text from text file of app folder.
public async Task<string> ReadTextFile(string targetFileName)
{
string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, targetFileName);
using FileStream InputStream = System.IO.File.OpenRead(targetFile);
using StreamReader reader = new StreamReader(InputStream);
return await reader.ReadToEndAsync();
}
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.