2

我正在尝试将现有文件保存到另一个地方。这是某种副本,但我想允许使用 FileSavePicker 为用户选择新的目的地。这是我的代码:

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)。如何正确保存文件?

4

2 回答 2

3

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.

于 2013-07-10T16:42:59.200 回答
0

您应该使用 FolderPicker 看到这个http://lunarfrog.com/blog/2011/10/07/winrt-file-and-folder-pickers/ 然后使用 StorageFile 的 CopyAsync() 或 MoveAsync() 方法。

于 2013-07-10T15:08:19.370 回答