如何使用FileSavePicker UWP从我的应用程序复制文件

时间:2016-11-01 20:24:29

标签: c# xaml uwp

我想在我的应用程序中将文件复制到FileSavePicker的文件夹中。我的代码:

var fileSavePicker = new FileSavePicker();
fileSavePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;

var filedb = new[] { ".db" };
fileSavePicker.FileTypeChoices.Add("DB", filedb);
fileSavePicker.SuggestedFileName = "BACKUPDB" + System.DateTime.Now.Day + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Year;

//var pathDB = Path.Combine(ApplicationData.Current.LocalFolder.Path, "file.db");

try
{
    StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("file.db");
    StorageFile localfile = await fileSavePicker.PickSaveFileAsync();
    fileSavePicker.SuggestedSaveFile = file;

    if (file != null)
    {
        Debug.WriteLine("file Exists!!"); 
        var fileToSave = await fileSavePicker.PickSaveFileAsync();

        ....

但我保存的文件大小为0。

我找到了如何保存文本文件,但我的文件不是文本。

1 个答案:

答案 0 :(得分:1)

您可以使用CopyAndReplaceAsync方法将本地文件复制到所选文件。

var fileSavePicker = new Windows.Storage.Pickers.FileSavePicker();
fileSavePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;

var filedb = new[] { ".db" };
fileSavePicker.FileTypeChoices.Add("DB", filedb);
fileSavePicker.SuggestedFileName = "BACKUPDB" + System.DateTime.Now.Day + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Year;

//var pathDB = Path.Combine(ApplicationData.Current.LocalFolder.Path, "file.db");

try
{
    StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("file.db");
    StorageFile localfile = await fileSavePicker.PickSaveFileAsync();

    if (file != null)
    {
        Debug.WriteLine("file Exists!!");
        await file.CopyAndReplaceAsync(localfile);
    }
}
catch(Exception ex)
{
    Debug.WriteLine(ex);
}