如何使用FileSavePicker保存现有StorageFile? [英] How to save existing StorageFile using FileSavePicker?

查看:184
本文介绍了如何使用FileSavePicker保存现有StorageFile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想现有的文件保存到另一个地方。这是某种形式的副本,但我想允许新的目标与FileSavePicker用户的选择。
这里是我的代码:

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



该文件将被创建之后,但空(0 KB)。如何正确保存文件?

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

推荐答案

我找到了解决方案,它比上面假设有一点点不同。它是基于复制和字节数组的写作

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



为什么这种方式比CopyAsync StorageFile()方法更好?
StorageFile方法允许文件只写在指定appxmanifest文件夹。到由PickSaveFileAsync()中选定的文件直接写入允许创建在用户想要的(如果他有写权限,当然该文件夹)任何地方的文件。我检查了这一点,它确实有效。
希望,这将帮助其他开发人员,如果他们将这个问题面对的问题。

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.

这篇关于如何使用FileSavePicker保存现有StorageFile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆