Путь к файлу в папке Downloads /document/raw:/storage/emulated/0/Download/MyFile.dat Путь к файлу в SdCard /document/1513-1812:MyFile.dat. Как я могу открыть эти файлы? Или как я могу получить их как Byte []?
Если вы хотите открыть файл из папки Download в 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);
}
}
}
Наконец, вы можете получить байт [] с помощью следующего кода:
private void btn1_Clicked(object sender, EventArgs e)
{
byte[] dataBuffer = DependencyService.Get<IFileSystem>().ReadAllByteS();
}
Обновление:
Если вы хотите выбрать один файл и открыть этот путь к файлу, я предлагаю вам использовать Xamarin.Plugin. FilePicker для выбора файла и получения пути к файлу.
Во-первых, установка Xamarin.Plugin.FilePicker с помощью пакета nuget ...
Затем изменение класса IFileSystem в PCL :
public interface IFileSystem
{
byte[] ReadAllByteS(string path);
}
и класс FileSystemImplementation в Android:
[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);
}
}
}
Наконец, вы можете получить байт []:
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);
}
}