Skip to content

Instantly share code, notes, and snippets.

@noxi515
Created December 15, 2018 17:29
Show Gist options
  • Save noxi515/a2d748b557d373c63c031ce7925d0976 to your computer and use it in GitHub Desktop.
Save noxi515/a2d748b557d373c63c031ce7925d0976 to your computer and use it in GitHub Desktop.
.NET Extensions IFileProvider for Android asset files.
using System;
using System.IO;
using System.Linq;
using Android.Content;
using Java.Lang;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Primitives;
namespace XamarinNetExtensions.Droid
{
internal class AndroidAssetFileProvider : IFileProvider
{
private readonly Context _context;
public AndroidAssetFileProvider(Context context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public IFileInfo GetFileInfo(string subpath)
{
var paths = subpath.Split(Path.PathSeparator);
var parent = Path.Combine(paths.SkipLast(1).ToArray());
if (_context.Assets.List(parent).All(path => path != subpath))
{
return new NotFoundFileInfo(subpath);
}
return new AndroidAssetFileInfo(_context, subpath);
}
public IDirectoryContents GetDirectoryContents(string subpath)
{
throw new UnsupportedOperationException("GetDirectoryContents is not supported.");
}
public IChangeToken Watch(string filter)
{
throw new UnsupportedOperationException("Watch is not supported.");
}
}
internal class AndroidAssetFileInfo : IFileInfo
{
private readonly Context _context;
private readonly string _filePath;
private long _length = -1L;
public AndroidAssetFileInfo(Context context, string filePath)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_filePath = filePath ?? throw new ArgumentNullException(nameof(filePath));
Name = filePath.Split(Path.PathSeparator).Last();
}
public Stream CreateReadStream()
{
return _context.Assets.Open(_filePath);
}
public bool Exists => true;
public long Length
{
get
{
if (_length != -1)
{
return _length;
}
using (var stream = CreateReadStream())
{
return _length = stream.Length;
}
}
}
public string PhysicalPath => $"file:///android_assets/{_filePath}";
public string Name { get; }
public DateTimeOffset LastModified { get; } = DateTimeOffset.MinValue;
public bool IsDirectory => false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment