gpt4 book ai didi

c# - 如何将文件从独立存储复制到“下载”文件夹?

转载 作者:行者123 更新时间:2023-12-04 14:19:13 25 4
gpt4 key购买 nike

我正在尝试将我的数据库文件从独立存储复制到下载文件夹(或用户可以访问的任何文件夹)。

目前我的数据库存储在:

/data/user/0/com.companyname.appname/files/Databases/MyDatabase.db

我尝试使用这段代码:

public string GetCustomFilePath(string folder, string filename)
{
var docFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var libFolder = Path.Combine(docFolder, folder);

if (!Directory.Exists(libFolder))
Directory.CreateDirectory(libFolder);

return Path.Combine(libFolder, filename);
}


var bas = GetDatabaseFilePath("MyDatabase.db");
var des = Path.Combine(Android.OS.Environment.DirectoryDownloads, "MyDatabase.db");
File.Copy(bas, des);

Android.OS.Environment.DirectoryDownloads 属性返回路径 Download,这是下载文件夹的名称。
但是 File.Copy() 抛出异常告诉

System.IO.DirectoryNotFoundException: Destination directory not found: Download.

我之前试过像这样使用斜线:/Download/MyDatabase.db 但没有成功。

有没有办法复制这样的文件?我需要任何许可吗?

最佳答案

1st) 是的,您确实需要权限才能写入外部存储。

你可以通过自己来获得所需的运行时权限:

或者通过第 3 方插件,例如 James Montemagno 的 PermissionsPlugin

2nd) 一旦您的用户接受可以写入外部存储,您可以使用:

Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads

获取设备公共(public)下载文件夹的路径,即使用Forms的依赖服务:

public interface IDownloadPath
{
string Get();
}

public class DownloadPath_Android : IDownloadPath
{
public string Get()
{
return Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
}
}

你最终会得到类似的东西:

public void Handle_Button(object sender, System.EventArgs e)
{
var fileName = "someFile.txt";
using (var stream = File.Create(Path.Combine(FileSystem.CacheDirectory, fileName)))
{
// just creating a dummy file to copy (in the cache dir using Xamarin.Essentials
}


var downloadPath = DependencyService.Get<IDownloadPath>().Get();
File.Copy(Path.Combine(FileSystem.CacheDirectory, fileName), downloadPath);
}

关于c# - 如何将文件从独立存储复制到“下载”文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56875215/

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