Xamarin 复制文件跨平台

Pat*_*chu 3 cross-platform xamarin

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

我找到了适用于 Xamarain.Android 和 iOS 的解决方案,但我想将它组合在一个 Portable 类中。

编辑
也许那里有更好的解决方案,但这是我用 PCL Sotrage 得到的。

        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();
Run Code Online (Sandbox Code Playgroud)

Ale*_*aro 5

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

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

public interface IFile {
    void Copy ( string fromFile, string toFile );
}
Run Code Online (Sandbox Code Playgroud)

在 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);
      }

  }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的 PCL 中,您可以调用

DependencyService.Get<IFile>().Copy("myfile", "newfile");
Run Code Online (Sandbox Code Playgroud)

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