Rodrigo Rodrigo - 1 month ago 13
C# Question

how to copy file from my app Using FileSavePicker UWP

I want copy file in my app to a folder with FileSavePicker. My Code:

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

....


but my saved file has size 0.

I found how to save text files but my file not is text.

tao tao
Answer

You can use CopyAndReplaceAsync method to copy your local file to the chosen file.

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