gpt4 book ai didi

Xamarin 复制文件跨平台

转载 作者:行者123 更新时间:2023-12-02 17:21:22 24 4
gpt4 key购买 nike

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

我找到了适用于 Xamarain.Android 和 iOS 的解决方案,但我希望将其合并到一个可移植类中。

编辑
也许有更好的解决方案,但这是我通过 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();

最佳答案

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

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

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

关于Xamarin 复制文件跨平台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42676408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com