Reputation: 25
I have an issue reading my .txt file in Xamarin and I have not find any solution that helps me, I also looked in Stack Overflow's suggestions before I published this.
My app is only Android and I want to randomize a line from the file, I have first made it in C# with console and looks like this =>
String[] Card = System.IO.File.ReadAllLines(@"D:\Cards.txt");
//string[] Card = { "one", "two", "Three", "Four", "Five", "Six" }; this is what is in the file.
However now when I try to do this in Xamarin the filepath is on my computer and not in my phone. I read at one site to make it an Asset as picture below shows. (I have also tried build action as AndroidAsset)
I am not sure now if my code is wrong or if it is possible to read from a file. Underneath are 2 examples that I have tried but there are a few more that I have tried but that code is deleted now.
String[] text = File.ReadAllLines(Assets.Open("Cards.txt"));
var currentPath = System.Environment.DataDirectory;
var Filename = Path.Combine(currentPath, "Cards.txt");
String[] text = File.ReadAllLines(Filename);
I have tried this now but it will not work as an array.
string[] content;
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader(assets.Open("Cards.txt")))
{
content[] = sr.ReadToEnd();
}
txtNumber.Text = content[3];
I want the result to be line 3 in the Cards.txt file which will be three.
Upvotes: 1
Views: 5548
Reputation: 25
i successfully solved it like this:
string content;
string[] cards = new string[] { "" }; //created a empty string array
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader(assets.Open("Cards.txt")))
{
content = sr.ReadToEnd();
}
cards = content.Split('\n'); //Split the content after a new row.
txtNumber.Text = cards[0]; //I changed the number inside cards[3] and it was showing correct value in the txt document.
Upvotes: 0
Reputation: 3048
Assuming that code lives inside of your Xamarin.Android folder, and it is not in the PCL library, you could try something like this:
string content;
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader (assets.Open ("read_asset.txt")))
{
content = sr.ReadToEnd ();
}
Upvotes: 2