Xamarin 跨平台复制文件

3

在Xamarin跨平台中,是否有可能复制文件?例如将SQLlite db3从一个目录复制到另一个目录。我只能获得文件的路径。

我已经找到了Xamarin.Android和iOS的解决方案,但我希望它们合并为一个可移植类。

编辑
也许有更好的解决方案,但这是我使用PCL存储得到的结果。

        IFile file = FileSystem.Current.GetFileFromPathAsync(src).Result;
        IFolder rootFolder = FileSystem.Current.GetFolderFromPathAsync(dest).Result;
        IFolder folder = rootFolder.CreateFolderAsync("MySubFolder", CreationCollisionOption.OpenIfExists).Result;
        IFile newFile = folder.CreateFileAsync("TodoItem.db3", CreationCollisionOption.GenerateUniqueName).Result;

        Stream str = file.OpenAsync(FileAccess.ReadAndWrite).Result;
        Stream newStr = newFile.OpenAsync(FileAccess.ReadAndWrite).Result;

        byte[] buffer = new byte[str.Length];
        int n;
        while ((n = str.Read(buffer, 0, buffer.Length)) != 0)
            newStr.Write(buffer, 0, n);
        str.Dispose();
        newStr.Dispose();
3个回答

5
我认为一个好的解决方案是使用DependencyService

例如,在PCL中创建一个接口。

public interface IFile {
    void Copy ( string fromFile, string toFile );
}

在Android中,这是平台特定的实现。
[assembly: Xamarin.Forms.Dependency (typeof (FileImplementation))]
namespace File.Droid {
  public class FileImplementation : IFile
  {
      public FileImplementation() {}

      public void Copy(string fromFile, string toFile)
      {
            System.IO.File.Copy(fromFile, toFile);
      }

  }
}

然后在你的PCL中,你可以调用:
DependencyService.Get<IFile>().Copy("myfile", "newfile");

使用.NETStandard,您可以直接在PCL项目中使用System.IO。

谢谢您的回复。但我想在共享代码中拥有逻辑。 - Patti Schu

1
回复内容存在敏感词^**$ Forms,我认为 Alessandro 的 DependencyService 解决方案很好,即使你没有使用 Forms,接口抽象的思想也同样适用。

0
为了避免在每个平台上处理不同的文件系统及其怪癖,您可以使用PCLStorage库在所有Xamarin.Forms平台上执行相当广泛的操作。
请在此处查看:https://github.com/dsplaisted/PCLStorage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接