繁体   English   中英

给定文件在本地存储中的路径,将文件转换为字节数组?

[英]Convert File To Byte Array Given Its Path In Local Storage?

以下集合包含本地存储中的映像路径

public ObservableCollection<string> Paths;

这些文件路径由用户选择,并在Xamarin Android Player上显示如下:

/storage/emulated/0/Download/img1.jpg
/storage/emulated/0/Download/img2.jpg

现在问题出在下面-我想将这些选定的图像(基于它们的路径)转换为字节数组,以将其上传到服务器。 在WPF / ASP.Net中,可以通过以下代码轻松实现:

byte[] Convert = File.ReadAllBytes("somepath...");

但是,似乎Xamarin.Forms中没有可用的东西。

为了在Xamarin.Forms中根据本地存储中的物理路径将图像转换为字节数组,我需要使用哪些函数?

------------------------------------------ -----------------------

UPDATE

@asp_net尝试实施您的解决方案:

在我的PCL项目中,我添加了以下两个文件:

public interface IFileSystem
{
    byte[] ReadAllByteS(string path);
}

public static class FileUtility
{
    public static IFileSystem FileSystem { get; set; }

    public static void SetUp(IFileSystem fs)
    {
        FileSystem = fs;
    }
}

在Android上,我添加了以下文件:

class SharedFileSytem : IFileSystem
{
    public byte[] ReadAllByteS(string path)
    {
        return File.ReadAllBytes(path);
    }
}

而且我在初始化/注册部分有些迷路-我很确定我需要在MainActivity.cs文件中添加一些内容

base.OnCreate(bundle);
Xamarin.Forms.Forms.Init(this, bundle);
//?
LoadApplication(new App());

因为当前,当我尝试在PCL代码中执行以下代码时

FileUtility.FileSystem.ReadAllByteS(somepath);

我收到以下错误消息:

"object reference not set to an instance of an object"

要澄清的事情:在您似乎使用的可移植类库中,System.IO不可用。 但是它当然可以在“ Xamarin.Forms”中使用。

选项:

  1. 使用共享项目而不是PCL。
  2. 从您的PCL调用平台特定的代码。

在PCL中定义一个接口。

public interface IFileSystem
{
    byte[] ReadAllByteS(string path);
}

在每个平台上(在这种情况下,在所有平台的共享项目中)实施它。

// Could also be "IosFileSystem" or "SharedFileSytem"
public class DroidFileSystem : IFileSystem
{
    public byte[] ReadAllbytes(string path)
    {
        return File.ReadAllBytes(path);
    }
}

在您的应用启动时注册您的实现(那里有库可以帮助您)。

public static class Utils
{
    public IFileSystem FileSystem { get; set; }

    public static void SetUp(IFileSystem fs)
    {
        FileSystem = fs;
    }
}

Utils存在于您的PCL中,但正在从AppDelegate或您的Main Activity中调用其SetUp方法。)

用它:

Utils.FileSystem.ReadAllBytes(...)

您可以将图像加载到内存流中并转换为数组,这样的事情应该可以工作

using (var streamReader = new StreamReader(path))
 {   
   using (var memoryStream = new MemoryStream())
    {
        streamReader.BaseStream.CopyTo(memoryStream);
        return memoryStream.ToArray();
    }

}
public async static Task<IFile> AsStorageFileAsync(this byte[] byteArray, string fileNameEx)
    {
        IFile file = await StorageData.LocalStorage().CreateFileAsync(fileNameEx, CreationCollisionOption.ReplaceExisting);
        using (var fileHandler = await file.OpenAsync(FileAccess.ReadAndWrite))
        {              
            byte[] dataBuffer = byteArray;
            await fileHandler.WriteAsync(dataBuffer, 0, dataBuffer.Length);
        }
        return file;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM