Reputation: 1002
I have a text file in my solution called "txtWords.txt", which I attempt to read with:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filePath = Path.Combine(path, "txtWords.txt");
In my experimenting, I've got the same file under both my C# App and the App.Android > Assets folder (set to AndroidAsset). I thought to put it in both locations to be safe.
System.IO.FileNotFoundException: Could not find file "/data/user/0/com.WSC/files/txtWords.txt"
I've read about using AssetManager but that gives me a "namespace could not be found error".
What am I doing wrong and what's the best way to read a text file for an app? This should be really easy so I'm doing something fairly basic wrong, I suppose.
Upvotes: 1
Views: 396
Reputation: 74209
Using Xamarin Essentials you can read a bundled/asset read-only file via your NetStd (Xamarin.Forms) library:
string wordsText;
using (var stream = await FileSystem.OpenAppPackageFileAsync("txtWords.txt"))
using (var reader = new StreamReader(stream))
{
var wordsText = await reader.ReadToEndAsync();
}
re: https://learn.microsoft.com/en-us/xamarin/essentials/file-system-helpers?tabs=android
Nuget: https://www.nuget.org/packages/Xamarin.Essentials
Upvotes: 1