Downloads 文件夹中文件的路径 /document/raw:/storage/emulated/0/Download/MyFile.dat SdCard 中的文件路径 /document/1513-1812:MyFile.dat。如何打开这些文件?或者我怎样才能将它们作为字节 []?
如果要从 Xamarin.Forms 的下载文件夹中打开文件,可以使用 DependencyService 来执行此操作。
首先,在 PCL 中创建类。
public interface IFileSystem
{
byte[] ReadAllByteS();
}
然后在android中实现:
[assembly: Dependency(typeof(FileSystemImplementation))]
namespace demo3.Droid
{
public class FileSystemImplementation : IFileSystem
{
public byte[] ReadAllByteS()
{
if (ContextCompat.CheckSelfPermission(MainActivity.mactivity, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted)
{
ActivityCompat.RequestPermissions(MainActivity.mactivity, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
return null;
}
var filePath = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads);
var path = System.IO.Path.Combine(filePath.AbsolutePath, "testfile/hello.txt");
return File.ReadAllBytes(path);
}
}
}
最后,可以通过以下代码获取byte[]:
private void btn1_Clicked(object sender, EventArgs e)
{
byte[] dataBuffer = DependencyService.Get<IFileSystem>().ReadAllByteS();
}
更新:
如果您想选择一个文件并获取此文件路径以打开,我建议您可以使用Xamarin.Plugin.FilePicker选择文件并获取文件路径。
首先,通过 nuget 包安装Xamarin.Plugin.FilePicker ...
然后修改 PCL 中的 IFileSystem 类:
public interface IFileSystem
{
byte[] ReadAllByteS(string path);
}
和 Android 中的 FileSystemImplementation 类:
[assembly: Dependency(typeof(FileSystemImplementation))]
namespace demo3.Droid
{
public class FileSystemImplementation : IFileSystem
{
public byte[] ReadAllByteS(string path)
{
if (ContextCompat.CheckSelfPermission(MainActivity.mactivity, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted)
{
ActivityCompat.RequestPermissions(MainActivity.mactivity, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
return null;
}
//var filePath = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads);
//var path = System.IO.Path.Combine(filePath.AbsolutePath, "testfile/hello.txt");
return File.ReadAllBytes(path);
}
}
}
最后可以得到byte[]:
private async void btn1_Clicked(object sender, EventArgs e)
{
FileData file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
string path = file.FilePath;
byte[] dataBuffer = DependencyService.Get<IFileSystem>().ReadAllByteS(path);
}
}