FIleSavePicker сохранение 0 байт файла Windows Phone 8
Итак, теперь мне сказали, что FileSavePicker создает только пустой файл, и что мне придется написать дополнительный код, чтобы затем записать его в файл. Я запустил Task WriteToFile после FileSavePicker, но я не уверен, как его завершить. С помощью FileSavePicker пользователь выбирает папку, в которую он хочет сохранить файл. Где я могу указать на это в коде WriteToFile и как именно в него поместить исходный файл? Все файлы, которые будут сохранены, упакованы с приложением. Я использую x.mp3 в качестве примера здесь.
public class SoundData : ViewModelBase
{
public string Title { get; set; }
public string FilePath { get; set; }
public RelayCommand<string> SaveSoundAs { get; set; }
private async void ExecuteSaveSoundAs(string soundPath)
{
string path = @"appdata:/x.mp3";
StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile file = await folder.GetFileAsync(path);
{
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedSaveFile = file;
savePicker.FileTypeChoices.Add("MP3", new List<string>() { ".mp3" });
savePicker.ContinuationData.Add("SourceSound", soundPath);
savePicker.SuggestedFileName = this.Title;
savePicker.PickSaveFileAndContinue();
}
}
public async void ContinueFileSavePicker(FileSavePickerContinuationEventArgs args)
{
string soundPath = (string)args.ContinuationData["SourceSound"];
StorageFile file = args.File;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
// write to file
await FileIO.WriteTextAsync(file, file.Name);
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
if (status == FileUpdateStatus.Complete) ;
}
}
public SoundData()
{
SaveSoundAs = new RelayCommand<string>(ExecuteSaveSoundAs);
}
}
}
1 ответ
Для Windows Phone вы должны следовать этой документации. Рабочий процесс немного изменился по сравнению с приложениями Silverlight. Ваше приложение больше не возобновляет работу, как раньше со старыми Задачами.
Вам не нужно выполнять все шаги в документе, но важной частью является над OnActivated
метод в App.xaml.cs. Там вы будете вызывать свой метод ContinueFileSavePicker.
Вот пример, который вы можете скачать, и который должен помочь.
Обновить
Если вы хотите сохранить файл, который вы отправите вместе с приложением, попробуйте следующий код для инициализации средства выбора.
// Get the local file that is shipped with the app
// file but be "content" and not "resource"
string path = @"Assets\Audio\Sound.mp3";
StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile file = await folder.GetFileAsync(path);
// Show the picker
FileSavePicker savePicker = new FileSavePicker();
// Set the file that will be saved
savePicker.SuggestedSaveFile = file;
savePicker.SuggestedFileName = "Sound";
savePicker.FileTypeChoices.Add("MP3", new List<string>() { ".mp3" });
savePicker.PickSaveFileAndContinue();
Вам также необходимо убедиться, что вы слушаете событие ContractActivation в PhoneApplicationService. Это событие вызывается (в приложениях 8.1 Silverlight), когда приложение возвращается из средства выбора. Здесь вы хотите вызвать свой метод ContinueFileSavePicker. Если вы хотите, вы всегда можете просто вставить логику там.
Подписаться на событие в xaml:
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
ContractActivated="Application_ContractActivated"
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
</Application.ApplicationLifetimeObjects>
И в App.xaml.cs:
private async void Application_ContractActivated(object sender, Windows.ApplicationModel.Activation.IActivatedEventArgs e)
{
var args = e as FileSavePickerContinuationEventArgs ;
if (args != null)
{
StorageFile file = args.File;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
// write to file
await FileIO.WriteTextAsync(file, file.Name);
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
}
}
}