Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Android, read a simple text file from internal storage/Download

I'm using Xamarin, and according to previous answers, this shall work:

string path = Path.Combine(Android.OS.Environment.DirectoryDownloads, "families.txt");
File.WriteAllText(path, "Write this text into a file!");

But it doesn't, I get and unhandled exception. I have set the permissions to read and write to external storage (even though this is internal).

I also tried it with this:

string content;
using (var streamReader = new StreamReader(@"file://" + path )) // with and without file://
{
    content = streamReader.ReadToEnd();
}

But I got the same unhandled exception.


UPDATE: The path is the problem, since I get the else part here:

Java.IO.File file = new Java.IO.File(path);
if (file.CanRead())
    testText.Text = "The file is there";
else
    testText.Text = "The file is NOT there\n" + path;

Which is weird, because the path seems to be correct. The exceptions: Could not find a part of the path: /Download/families.txt


UPDATE2: On external storage, it works, with the same code... Might it be my device's problem? That would be great, cause I tested the external storage version on my friend's phone, but mine doesn't have external storage (OnePlus One), so I'm still looking for a solution (if there's any).
like image 243
hungariandude Avatar asked Dec 25 '22 13:12

hungariandude


1 Answers

Finally found a solution.

var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filename = Path.Combine(path.ToString(), "myfile.txt");

The path was the problem, now with a simple streamwriter it works like magic.

try
{
      using (var streamWriter = new StreamWriter(filename, true))
      {
             streamWriter.WriteLine("I am working!");
      }
}
catch { ... }
like image 197
hungariandude Avatar answered Dec 29 '22 10:12

hungariandude