How to save existing StorageFile using FileSavePic

2019-02-11 02:43发布

问题:

I'm trying to save existing file to another place. It's some kind of copy, but I want to allow choosing of new destination to user with FileSavePicker. Here is my code:

StorageFile currentImage = await StorageFile.GetFileFromPathAsync(item.UniqueId);
var savePicker = new FileSavePicker();
savePicker.FileTypeChoices.Add("JPEG-Image",new List<string>() { ".jpg"});
savePicker.FileTypeChoices.Add("PNG-Image", new List<string>() { ".png" });
savePicker.SuggestedSaveFile = currentImage;
savePicker.SuggestedFileName = currentImage.Name;
var file = await savePicker.PickSaveFileAsync();

After that the file will be created, but it empty (0 KB). How to save file correctly?

回答1:

I found the solution and it's a little bit different than presumed above. It is based on copying and writing of byte arrays.

        var curItem = (SampleDataItem)flipView.SelectedItem;
        StorageFile currentImage = await StorageFile.GetFileFromPathAsync(curItem.UniqueId);
        byte[] buffer;
        Stream stream = await currentImage.OpenStreamForReadAsync();
        buffer = new byte[stream.Length];
        await stream.ReadAsync(buffer, 0, (int)stream.Length); 
        var savePicker = new FileSavePicker();
        savePicker.FileTypeChoices.Add("JPEG-Image",new List<string>() { ".jpg"});
        savePicker.FileTypeChoices.Add("PNG-Image", new List<string>() { ".png" });
        savePicker.SuggestedSaveFile = currentImage;
        savePicker.SuggestedFileName = currentImage.Name;
        var file = await savePicker.PickSaveFileAsync();
        if (file != null)
        {
            CachedFileManager.DeferUpdates(file);
            await FileIO.WriteBytesAsync(file, buffer);
            CachedFileManager.CompleteUpdatesAsync(file);
        }

Why this way is better than CopyAsync() method of StorageFile? StorageFile methods allow to write files only to folders that specified in appxmanifest. Direct writing to the file that was selected by PickSaveFileAsync() allows to create a file at any place that user want (if he has write access to that folder of course). I checked this and it really works. Hope, it will help other developers if they will face with this issue.



回答2:

You should use FolderPicker see this http://lunarfrog.com/blog/2011/10/07/winrt-file-and-folder-pickers/ and then use CopyAsync() or MoveAsync() methods of StorageFile.