UndefinedReference
UndefinedReference

Reputation: 1253

Can't Access File In file:///android_asset

I have a file myfile.vtpk in my application's "Assets" folder.

I'm trying to load this file file in my application using the following:

            Uri vtpkUri = new Uri("file:///android_asset/myfile.vtpk");
            ArcGISVectorTiledLayer vtpkLayer = new ArcGISVectorTiledLayer(vtpkUri);

            MyMapView.Map.OperationalLayers.Add(vtpkLayer);

I get no error, but the file is never loaded.

How can I access this file in Android?

Thanks!

Upvotes: 1

Views: 2563

Answers (1)

jgoldberger - MSFT
jgoldberger - MSFT

Reputation: 6088

Since a file in your Assets folder is compiled into your APK, there is no "Uri" for a file in your assets folder, or any file in your APK for that matter. If you need to be able to pass a Uri, you would want to copy the Asset to your Document or other folder for your app and then get the Uri.

First create a method to take an read stream and write write stream and write your asset to a file:

private void ReadWriteStream(Stream readStream, Stream writeStream)
{
    int Length = 256;
    Byte[] buffer = new Byte[Length];
    int bytesRead = readStream.Read(buffer, 0, Length);
    // write the required bytes
    while (bytesRead > 0)
    {
          writeStream.Write(buffer, 0, bytesRead);
           bytesRead = readStream.Read(buffer, 0, Length);
    }
    readStream.Close();
    writeStream.Close();
}

Then get the read stream from the asset:

AssetFileDescriptor afd = Assets.OpenFd("filenameinAssetsfolder.ext");
var readStream = afd.CreateOutputStream();

Then create the path for the file and the write stream:

// This will be your final file path
var pathToWriteFile = 
    Path.Combine (System.Environment.GetFolderPath 
    (System.Environment.SpecialFolder.Personal), 
    "filenametowrite.ext"); 
FileStream writeStream = 
    new FileStream(pathToWriteFile, 
    FileMode.OpenOrCreate, 
    FileAccess.Write);

And finally call the copy method created above:

ReadWriteStream(readStream, writeStream);

Now you should be able to access the file with the path in pathToWriteFile.

EDIT: As per the comment below, try the following instead of getting an AssetFileDescriptor first. Replace:

AssetFileDescriptor afd = Assets.OpenFd("filenameinAssetsfolder.ext");
var readStream = afd.CreateOutputStream();

with:

Stream readStream = Assets.Open("filenameinAssetsfolder.ext");

Upvotes: 3

Related Questions