1

I'm new on this website!

I'm experiencing some problem in Xamarin Android opening a file. I have to open a file which contains a list of foods and relative calories, split by some delimiter chars.

When I wrote this code for Xamarin iOS I didn't have any problem with the following code:

outputText.Text = "The selectable foods are:\n\n"; foreach (string line in File.ReadLines("Cibi.txt")) { string[] cibsel = line.Split(delimiterChars); outputText.Text += cibsel[0] + "\n"; } 

Of course in iOS the file was stored inside Resources folder.

But when I started to write the same code in Xamarin Android I'm starting to experiencing some errors.

First the program rusn into an exception because Visaul Studio can't find the path of the file (stored inside Assets folder). Then I found on Xamarin tutorial that suggested to use Streamreader.ReadLine() instead File.Readlines(), but I obtain the following error:

Can not convert type 'char' to 'string'.

The program must only read a food and calories from a file and return, as output, only the name. How I can do this without experiencing that kind of error?

Thanks in advance!

Enrico

1 Answer 1

2

The Xamarin docs explain how to access files in Android. Basically, you need to add the file to the Assets folder and set it's build action to AndroidAsset. Then in your code you can read the file like this:

string line; using (StreamReader sr = new StreamReader (Assets.Open (my_file_name))) { do { line = sr.ReadLine(); string[] cibsel = line.Split(delimiterChars); outputText.Text += cibsel[0] + "\n"; } while(line != null); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jason! Now I solved the problem for reading the file, and the program works fine. But now I have a similar problem for write on the same file, because my program also allows to update the food file. I used the stremwriter, using of sure the Assets.Open function, but when I debug and I try to update the file I receive the following exception: System.ArgumentException: Can not write to stream. I can't understand how I can solve it... Thanks a lot for the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.