2

I am current writing a small tool with Xamarin Form (Android) that takes some file content and displays them in some specific way. In these files i have some cross-links (e.g. jpeg-images) that should be embedded in the display of the file.

To get the main file i am using "CrossFilePicker.Current.PickFile()". It returns an "FileData" object, which allready has the main file contents, plus the URI of that file.

If there is a cross-link in that file i can assume that the linked file is in the same folder as the main file.

My idea (taking jpeg as example) to get the base-folder of the file and append the name of the jpeg and then open the image as stream:

ImagePath = Path.Combine(baseFolder.Trim(), imageFile.Trim());

try
{
    fileStream = new FileStream(ImagePath, FileMode.Open, FileAccess.Read);
    fileStream.DisposeWith(Disposables);

    ImageSource = ImageSource.FromStream(() => fileStream);
    ShowImage = true;
}
catch
{
    // Ignore
}

Unfortunatelly FileStream failes, and claims it could not find the containing directory.

The path towards to JPG look like this:

/document/0F1E-120D/TestData/P1060371.jpg

The file path i get from the Picker is:

content://com.android.externalstorage.documents/document/0F1E-120D%3ATestData%2FTestFile.txt

Using that a an URI i can extract the local path:

/document/0F1E-120D:TestData/TestFile.txt

When removing the file name i get

/document/0F1E-120D:TestData

Obviously that path is invalid...

Any hint on how i can get a valid path i can feed into the FileStream for reading the file? Any more hints about that permissions i have to take care? Currently i have set READ_EXTERNAL_STORAGE

emvoll
  • 99
  • 7
  • Do you want to access the path like `/storage/emulated/0/Android/data/com.companyname.app/files/Documents` or `/storage/emulated/0/Documents`? If you want to access the seond path, you can get it by `Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDocuments).AbsolutePath` – Leon Feb 17 '20 at 09:27
  • What t´d rather like to do is to allow the use to select the directory. I´ve created a simple folder browser to set the directory. I´ve done some changes meanwhile and the path looks like /storage/1EE7-170F/TestFile.txt That is working for now to read the files... – emvoll Feb 18 '20 at 16:58
  • Ok, Thanks for your sharing. – Leon Feb 19 '20 at 07:32

1 Answers1

0

If you use NetStandard2.0 you use this code

System.IO.File.ReadAllBytes(filePath);

it also applied to specific platform(e.g: Xamarin.Android, Xamarin.iOS, etc)

cahyo
  • 597
  • 2
  • 5
  • 14
  • Accessing the file is not the problem. The problem is that i somehow need to find out the filepath from the URI mentioned above. – emvoll Feb 14 '20 at 13:47
  • If you got the URI from `onActivityResult` you can [try this](https://stackoverflow.com/a/5309965/4778712) – cahyo Feb 17 '20 at 06:04