Xamarin Forms for Android, как поделиться и открыть файл? - PullRequest
0 голосов
/ 19 апреля 2020

Я новичок в Xamarin и пытаюсь понять это. Есть два момента, в которых я не могу понять. Сначала я пытаюсь поделиться файлом:

byte[] fileArray = ....
var sharingIntent = new Intent(Intent.ActionSend);
sharingIntent.SetType("application/octet-stream");
sharingIntent.PutExtra(Intent.ExtraStream, fileArray);
StartActivity(Intent.CreateChooser(sharingIntent, "Send file"));

Я получаю сообщение об ошибке: Ошибка загрузки. Запрос не содержит данных.

Во-вторых, я выяснил, как открыть файл и как получить к нему путь: защищенное переопределение void OnActivityResult (int requestCode, Result resultCode, Intent intent)

protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
    base.OnActivityResult(requestCode, resultCode, intent);
    switch (resultCode)
    {
        case Result.Ok:
            string path = intent.Data.Path;
         break;
    }
}

Путь к файлу в папке Downloads /document/raw:/storage/emulated/0/Download/MyFile.dat Путь к файлу в SdCard /document/1513-1812:MyFile.dat

How я могу открыть эти файлы? Или как я могу получить их как Байт []?

Буду рад любой помощи, спасибо.

1 Ответ

0 голосов
/ 20 апреля 2020

Путь к файлу в папке 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);             
        }


    }
...