How to save existing StorageFile using FileSavePicker?

流过昼夜 提交于 2019-11-29 23:29:48

问题


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.



来源:https://stackoverflow.com/questions/17571152/how-to-save-existing-storagefile-using-filesavepicker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!