I need to copy the content in a folder located in Assets
in my Xamarin.Android project. There are more than 10 files in my Content
folder and I need to create a folder called Models
in my application's data folder and copy the content into it. So I have done following steps.
private async Task copyFileAsync()
{
var outputName = Application.Context.GetExternalFilesDir("").AbsolutePath + "/Models";
if (!System.IO.File.Exists (outputName))
{
Directory.CreateDirectory(outputName);
}
AssetManager assetManager = this.Assets;
String[] files = null;
try
{
files = assetManager.List("html/Model1/Content");
}
catch (System.IO.IOException e)
{
System.Console.WriteLine("tag", "Failed to get asset file list.", e);
}
foreach (String filename in files)
{
string filePath = System.IO.Path.Combine(outputName, filename);
using (var fileAssetStream = assetManager.Open(filename))
using (var fileStream = new FileStream (filePath, FileMode.OpenOrCreate))
{
await copyInToLocationAsync(fileAssetStream, fileStream, filePath);
}
System.Console.WriteLine("------COPIED------------------------");
}
}
private async Task copyInToLocationAsync(Stream fileAssetStream, Stream fileStream, string path)
{
byte[] buffer = new byte[1024];
int b = buffer.Length;
int length;
while ((length = await fileAssetStream.ReadAsync(buffer, 0, b)) > 0)
{
await fileStream.WriteAsync(buffer, 0, length);
}
fileStream.Flush();
fileStream.Close();
fileAssetStream.Close();
}
then in my OnCreate()
method I am calling await copyFileAsync();
. But my problem is I am getting a run time exception at using (var fileAssetStream = assetManager.Open(filename))
in CopyFileAsync()
.
This is the exception I get and 0.pf is the 1st file in my Content
folder. What is the reason for this and how can I overcome this?
You lost the file's path. According to your code, the file 0.pf is in the path /Assets/html/Model1/Content. So you should pass the full path when you use the assetManager.Open
. Such as:
using (var fileAssetStream = assetManager.Open("html/Model1/Content/"+filename))