简体   繁体   中英

How can I copy a file from the isolated storage to the Downloads folder?

I'm trying to copy my database file from the isolated storage to the Download folder (or any folder that the user can access).

Currently my database is stored in:

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

I tried to use this code:

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

The Android.OS.Environment.DirectoryDownloads property returns the path Download , which is the name of the downloads folder.
But File.Copy() throws an exception telling

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

I tried to use a slash before like this: /Download/MyDatabase.db with no luck.

Is there any way to copy a file like that? Do I need any permission?

1st) Yes, you do need permissions to write to external storage.

You can get the runtime time permission required by doing it yourself:

Or via a 3rd-party plugin, such as James Montemagno's PermissionsPlugin

2nd) Once your user accepts that it is ok to write to external storage, you can use:

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

To obtain the path of the device's public Download folder, ie using a Forms' dependency service:

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

You end up with something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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